3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
19 #include "BranchList.h"
21 #include "buffer_funcs.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "CoordCache.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
34 #include "InsetIterator.h"
36 #include "LaTeXFeatures.h"
37 #include "LayoutFile.h"
44 #include "MetricsInfo.h"
45 #include "Paragraph.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
50 #include "TextClass.h"
51 #include "TextMetrics.h"
53 #include "TocBackend.h"
55 #include "WordLangTuple.h"
57 #include "insets/InsetBibtex.h"
58 #include "insets/InsetCommand.h" // ChangeRefs
59 #include "insets/InsetExternal.h"
60 #include "insets/InsetGraphics.h"
61 #include "insets/InsetRef.h"
62 #include "insets/InsetText.h"
63 #include "insets/InsetNote.h"
65 #include "frontends/alert.h"
66 #include "frontends/Application.h"
67 #include "frontends/Delegates.h"
68 #include "frontends/FontMetrics.h"
69 #include "frontends/Painter.h"
70 #include "frontends/Selection.h"
72 #include "graphics/Previews.h"
74 #include "support/convert.h"
75 #include "support/debug.h"
76 #include "support/ExceptionMessage.h"
77 #include "support/filetools.h"
78 #include "support/gettext.h"
79 #include "support/lstrings.h"
80 #include "support/Package.h"
81 #include "support/types.h"
91 using namespace lyx::support;
95 namespace Alert = frontend::Alert;
99 /// Return an inset of this class if it exists at the current cursor position
101 T * getInsetByCode(Cursor const & cur, InsetCode code)
103 DocIterator it = cur;
104 Inset * inset = it.nextInset();
105 if (inset && inset->lyxCode() == code)
106 return static_cast<T*>(inset);
111 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
114 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
115 docstring const & contents)
117 DocIterator tmpdit = dit;
120 Inset const * inset = tmpdit.nextInset();
122 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
123 && (contents.empty() ||
124 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
128 tmpdit.forwardInset();
135 /// Looks for next inset with one of the given codes.
136 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
140 DocIterator tmpdit = dit;
141 tmpdit.forwardInset();
146 Inset const * inset = tmpdit.nextInset();
148 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
149 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
153 if (!findNextInset(tmpdit, codes, contents)) {
154 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
155 Inset * inset = &tmpdit.bottom().inset();
156 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
157 if (!findNextInset(tmpdit, codes, contents))
169 /// Looks for next inset with the given code
170 void findInset(DocIterator & dit, InsetCode code, bool same_content)
172 findInset(dit, vector<InsetCode>(1, code), same_content);
176 /// Moves cursor to the next inset with one of the given codes.
177 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
180 Cursor tmpcur = bv->cursor();
181 if (!findInset(tmpcur, codes, same_content)) {
182 bv->cursor().message(_("No more insets"));
186 tmpcur.clearSelection();
187 bv->setCursor(tmpcur);
192 /// Moves cursor to the next inset with given code.
193 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
195 gotoInset(bv, vector<InsetCode>(1, code), same_content);
199 /// A map from a Text to the associated text metrics
200 typedef map<Text const *, TextMetrics> TextMetricsCache;
202 enum ScreenUpdateStrategy {
212 /////////////////////////////////////////////////////////////////////
216 /////////////////////////////////////////////////////////////////////
218 struct BufferView::Private
220 Private(BufferView & bv): wh_(0), cursor_(bv),
221 anchor_pit_(0), anchor_ypos_(0),
222 inlineCompletionUniqueChars_(0),
223 last_inset_(0), bookmark_edit_position_(0), gui_(0)
227 ScrollbarParameters scrollbarParameters_;
229 ScreenUpdateStrategy update_strategy_;
231 CoordCache coord_cache_;
233 /// Estimated average par height for scrollbar.
235 /// this is used to handle XSelection events in the right manner.
244 pit_type anchor_pit_;
248 vector<int> par_height_;
251 DocIterator inlineCompletionPos_;
253 docstring inlineCompletion_;
255 size_t inlineCompletionUniqueChars_;
257 /// keyboard mapping object.
260 /// last visited inset.
261 /** kept to send setMouseHover(false).
262 * Not owned, so don't delete.
266 // cache for id of the paragraph which was edited the last time
267 int bookmark_edit_position_;
269 mutable TextMetricsCache text_metrics_;
272 /** Not owned, so don't delete.
274 frontend::GuiBufferViewDelegate * gui_;
276 /// Cache for Find Next
277 FuncRequest search_request_cache_;
281 BufferView::BufferView(Buffer & buf)
282 : width_(0), height_(0), full_screen_(false), buffer_(buf),
283 d(new Private(*this))
285 d->xsel_cache_.set = false;
286 d->intl_.initKeyMapper(lyxrc.use_kbmap);
288 d->cursor_.setBuffer(&buf);
289 d->cursor_.push(buffer_.inset());
290 d->cursor_.resetAnchor();
291 d->cursor_.setCurrentFont();
293 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
294 thePreviews().generateBufferPreviews(buffer_);
298 BufferView::~BufferView()
300 // current buffer is going to be switched-off, save cursor pos
301 // Ideally, the whole cursor stack should be saved, but session
302 // currently can only handle bottom (whole document) level pit and pos.
303 // That is to say, if a cursor is in a nested inset, it will be
304 // restore to the left of the top level inset.
305 LastFilePosSection::FilePos fp;
306 fp.pit = d->cursor_.bottom().pit();
307 fp.pos = d->cursor_.bottom().pos();
308 theSession().lastFilePos().save(buffer_.fileName(), fp);
314 int BufferView::rightMargin() const
316 // The additional test for the case the outliner is opened.
318 !lyxrc.full_screen_limit ||
319 width_ < lyxrc.full_screen_width + 20)
322 return (width_ - lyxrc.full_screen_width) / 2;
326 int BufferView::leftMargin() const
328 return rightMargin();
332 bool BufferView::isTopScreen() const
334 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
338 bool BufferView::isBottomScreen() const
340 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
344 Intl & BufferView::getIntl()
350 Intl const & BufferView::getIntl() const
356 CoordCache & BufferView::coordCache()
358 return d->coord_cache_;
362 CoordCache const & BufferView::coordCache() const
364 return d->coord_cache_;
368 Buffer & BufferView::buffer()
374 Buffer const & BufferView::buffer() const
380 bool BufferView::fitCursor()
382 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
383 frontend::FontMetrics const & fm =
384 theFontMetrics(d->cursor_.getFont().fontInfo());
385 int const asc = fm.maxAscent();
386 int const des = fm.maxDescent();
387 Point const p = getPos(d->cursor_, d->cursor_.boundary());
388 if (p.y_ - asc >= 0 && p.y_ + des < height_)
395 void BufferView::processUpdateFlags(Update::flags flags)
397 // last_inset_ points to the last visited inset. This pointer may become
398 // invalid because of keyboard editing. Since all such operations
399 // causes screen update(), I reset last_inset_ to avoid such a problem.
401 // This is close to a hot-path.
402 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
403 << "[fitcursor = " << (flags & Update::FitCursor)
404 << ", forceupdate = " << (flags & Update::Force)
405 << ", singlepar = " << (flags & Update::SinglePar)
406 << "] buffer: " << &buffer_);
408 buffer_.updateMacros();
410 // Now do the first drawing step if needed. This consists on updating
411 // the CoordCache in updateMetrics().
412 // The second drawing step is done in WorkArea::redraw() if needed.
414 // Case when no explicit update is requested.
416 // no need to redraw anything.
417 d->update_strategy_ = NoScreenUpdate;
421 if (flags == Update::Decoration) {
422 d->update_strategy_ = DecorationUpdate;
427 if (flags == Update::FitCursor
428 || flags == (Update::Decoration | Update::FitCursor)) {
429 // tell the frontend to update the screen if needed.
434 if (flags & Update::Decoration) {
435 d->update_strategy_ = DecorationUpdate;
439 // no screen update is needed.
440 d->update_strategy_ = NoScreenUpdate;
444 bool const full_metrics = flags & Update::Force || !singleParUpdate();
447 // We have to update the full screen metrics.
450 if (!(flags & Update::FitCursor)) {
451 // Nothing to do anymore. Trigger a redraw and return
456 // updateMetrics() does not update paragraph position
457 // This is done at draw() time. So we need a redraw!
461 // The cursor is off screen so ensure it is visible.
468 void BufferView::updateScrollbar()
470 if (height_ == 0 && width_ == 0)
473 // We prefer fixed size line scrolling.
474 d->scrollbarParameters_.single_step = defaultRowHeight();
475 // We prefer full screen page scrolling.
476 d->scrollbarParameters_.page_step = height_;
478 Text & t = buffer_.text();
479 TextMetrics & tm = d->text_metrics_[&t];
481 LYXERR(Debug::GUI, " Updating scrollbar: height: "
482 << t.paragraphs().size()
483 << " curr par: " << d->cursor_.bottom().pit()
484 << " default height " << defaultRowHeight());
486 size_t const parsize = t.paragraphs().size();
487 if (d->par_height_.size() != parsize) {
488 d->par_height_.clear();
489 // FIXME: We assume a default paragraph height of 2 rows. This
490 // should probably be pondered with the screen width.
491 d->par_height_.resize(parsize, defaultRowHeight() * 2);
494 // Look at paragraph heights on-screen
495 pair<pit_type, ParagraphMetrics const *> first = tm.first();
496 pair<pit_type, ParagraphMetrics const *> last = tm.last();
497 for (pit_type pit = first.first; pit <= last.first; ++pit) {
498 d->par_height_[pit] = tm.parMetrics(pit).height();
499 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
500 << d->par_height_[pit]);
503 int top_pos = first.second->position() - first.second->ascent();
504 int bottom_pos = last.second->position() + last.second->descent();
505 bool first_visible = first.first == 0 && top_pos >= 0;
506 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
507 if (first_visible && last_visible) {
508 d->scrollbarParameters_.min = 0;
509 d->scrollbarParameters_.max = 0;
513 d->scrollbarParameters_.min = top_pos;
514 for (size_t i = 0; i != size_t(first.first); ++i)
515 d->scrollbarParameters_.min -= d->par_height_[i];
516 d->scrollbarParameters_.max = bottom_pos;
517 for (size_t i = last.first + 1; i != parsize; ++i)
518 d->scrollbarParameters_.max += d->par_height_[i];
520 d->scrollbarParameters_.position = 0;
521 // The reference is the top position so we remove one page.
522 if (lyxrc.scroll_below_document)
523 d->scrollbarParameters_.max -= minVisiblePart();
525 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
529 ScrollbarParameters const & BufferView::scrollbarParameters() const
531 return d->scrollbarParameters_;
535 docstring BufferView::toolTip(int x, int y) const
537 // Get inset under mouse, if there is one.
538 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
540 // No inset, no tooltip...
542 return covering_inset->toolTip(*this, x, y);
546 docstring BufferView::contextMenu(int x, int y) const
548 //If there is a selection, return the containing inset menu
549 if (d->cursor_.selection())
550 return d->cursor_.inset().contextMenu(*this, x, y);
552 // Get inset under mouse, if there is one.
553 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
555 return covering_inset->contextMenu(*this, x, y);
557 return buffer_.inset().contextMenu(*this, x, y);
561 void BufferView::scrollDocView(int value)
563 int const offset = value - d->scrollbarParameters_.position;
565 // No scrolling at all? No need to redraw anything
569 // If the offset is less than 2 screen height, prefer to scroll instead.
570 if (abs(offset) <= 2 * height_) {
571 d->anchor_ypos_ -= offset;
577 // cut off at the top
578 if (value <= d->scrollbarParameters_.min) {
579 DocIterator dit = doc_iterator_begin(&buffer_);
581 LYXERR(Debug::SCROLLING, "scroll to top");
585 // cut off at the bottom
586 if (value >= d->scrollbarParameters_.max) {
587 DocIterator dit = doc_iterator_end(&buffer_);
590 LYXERR(Debug::SCROLLING, "scroll to bottom");
594 // find paragraph at target position
595 int par_pos = d->scrollbarParameters_.min;
597 for (; i != int(d->par_height_.size()); ++i) {
598 par_pos += d->par_height_[i];
599 if (par_pos >= value)
603 if (par_pos < value) {
604 // It seems we didn't find the correct pit so stay on the safe side and
606 LYXERR0("scrolling position not found!");
607 scrollDocView(d->scrollbarParameters_.max);
611 DocIterator dit = doc_iterator_begin(&buffer_);
613 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
618 // FIXME: this method is not working well.
619 void BufferView::setCursorFromScrollbar()
621 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
623 int const height = 2 * defaultRowHeight();
624 int const first = height;
625 int const last = height_ - height;
627 Cursor const & oldcur = d->cursor_;
629 switch (cursorStatus(oldcur)) {
637 int const y = getPos(oldcur, oldcur.boundary()).y_;
638 newy = min(last, max(y, first));
642 // We reset the cursor because cursorStatus() does not
643 // work when the cursor is within mathed.
645 cur.reset(buffer_.inset());
646 tm.setCursorFromCoordinates(cur, 0, newy);
648 // update the bufferview cursor and notify insets
649 // FIXME: Care about the d->cursor_ flags to redraw if needed
650 Cursor old = d->cursor_;
652 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
654 d->cursor_.fixIfBroken();
658 Change const BufferView::getCurrentChange() const
660 if (!d->cursor_.selection())
661 return Change(Change::UNCHANGED);
663 DocIterator dit = d->cursor_.selectionBegin();
664 return dit.paragraph().lookupChange(dit.pos());
668 // this could be used elsewhere as well?
669 // FIXME: This does not work within mathed!
670 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
672 Point const p = getPos(dit, dit.boundary());
675 if (p.y_ > workHeight())
681 void BufferView::bookmarkEditPosition()
683 // Don't eat cpu time for each keystroke
684 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
687 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
691 void BufferView::saveBookmark(unsigned int idx)
693 // tentatively save bookmark, id and pos will be used to
694 // acturately locate a bookmark in a 'live' lyx session.
695 // pit and pos will be updated with bottom level pit/pos
697 theSession().bookmarks().save(
699 d->cursor_.bottom().pit(),
700 d->cursor_.bottom().pos(),
701 d->cursor_.paragraph().id(),
706 // emit message signal.
707 message(_("Save bookmark"));
711 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
712 int top_id, pos_type top_pos)
714 bool success = false;
717 d->cursor_.clearSelection();
719 // if a valid par_id is given, try it first
720 // This is the case for a 'live' bookmark when unique paragraph ID
721 // is used to track bookmarks.
723 dit = buffer_.getParFromID(top_id);
725 dit.pos() = min(dit.paragraph().size(), top_pos);
726 // Some slices of the iterator may not be
727 // reachable (e.g. closed collapsable inset)
728 // so the dociterator may need to be
729 // shortened. Otherwise, setCursor may crash
730 // lyx when the cursor can not be set to these
732 size_t const n = dit.depth();
733 for (size_t i = 0; i < n; ++i)
734 if (!dit[i].inset().editable()) {
742 // if top_id == 0, or searching through top_id failed
743 // This is the case for a 'restored' bookmark when only bottom
744 // (document level) pit was saved. Because of this, bookmark
745 // restoration is inaccurate. If a bookmark was within an inset,
746 // it will be restored to the left of the outmost inset that contains
748 if (bottom_pit < int(buffer_.paragraphs().size())) {
749 dit = doc_iterator_begin(&buffer_);
751 dit.pit() = bottom_pit;
752 dit.pos() = min(bottom_pos, dit.paragraph().size());
757 // Note: only bottom (document) level pit is set.
759 // set the current font.
760 d->cursor_.setCurrentFont();
761 // To center the screen on this new position we need the
762 // paragraph position which is computed at draw() time.
763 // So we need a redraw!
773 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
775 if (lyxrc.rtl_support) {
776 if (d->cursor_.real_current_font.isRightToLeft()) {
777 if (d->intl_.keymap == Intl::PRIMARY)
778 d->intl_.keyMapSec();
780 if (d->intl_.keymap == Intl::SECONDARY)
781 d->intl_.keyMapPrim();
785 d->intl_.getTransManager().translateAndInsert(c, t, cur);
789 int BufferView::workWidth() const
795 void BufferView::recenter()
797 showCursor(d->cursor_, true);
801 void BufferView::showCursor()
803 showCursor(d->cursor_, false);
807 void BufferView::showCursor(DocIterator const & dit, bool recenter)
809 if (scrollToCursor(dit, recenter))
814 void BufferView::scrollToCursor()
816 scrollToCursor(d->cursor_, false);
820 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
822 // We are not properly started yet, delay until resizing is
827 LYXERR(Debug::SCROLLING, "recentering!");
829 CursorSlice const & bot = dit.bottom();
830 TextMetrics & tm = d->text_metrics_[bot.text()];
832 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
833 int bot_pit = bot.pit();
834 if (bot_pit > max_pit) {
835 // FIXME: Why does this happen?
836 LYXERR0("bottom pit is greater that max pit: "
837 << bot_pit << " > " << max_pit);
841 if (bot_pit == tm.first().first - 1)
842 tm.newParMetricsUp();
843 else if (bot_pit == tm.last().first + 1)
844 tm.newParMetricsDown();
846 if (tm.contains(bot_pit)) {
847 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
848 LASSERT(!pm.rows().empty(), /**/);
849 // FIXME: smooth scrolling doesn't work in mathed.
850 CursorSlice const & cs = dit.innerTextSlice();
851 int offset = coordOffset(dit, dit.boundary()).y_;
852 int ypos = pm.position() + offset;
853 Dimension const & row_dim =
854 pm.getRow(cs.pos(), dit.boundary()).dimension();
857 scrolled = scroll(ypos - height_/2);
858 else if (ypos - row_dim.ascent() < 0)
859 scrolled = scrollUp(- ypos + row_dim.ascent());
860 else if (ypos + row_dim.descent() > height_)
861 scrolled = scrollDown(ypos - height_ + defaultRowHeight() );
863 // else, nothing to do, the cursor is already visible so we just return.
871 // fix inline completion position
872 if (d->inlineCompletionPos_.fixIfBroken())
873 d->inlineCompletionPos_ = DocIterator();
875 tm.redoParagraph(bot_pit);
876 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
877 int offset = coordOffset(dit, dit.boundary()).y_;
879 d->anchor_pit_ = bot_pit;
880 CursorSlice const & cs = dit.innerTextSlice();
881 Dimension const & row_dim =
882 pm.getRow(cs.pos(), dit.boundary()).dimension();
885 d->anchor_ypos_ = height_/2;
886 else if (d->anchor_pit_ == 0)
887 d->anchor_ypos_ = offset + pm.ascent();
888 else if (d->anchor_pit_ == max_pit)
889 d->anchor_ypos_ = height_ - offset - row_dim.descent();
890 else if (offset > height_)
891 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
893 d->anchor_ypos_ = defaultRowHeight() * 2;
900 void BufferView::updateLayout(DocumentClass const * const oldlayout)
902 message(_("Converting document to new document class..."));
904 StableDocIterator backcur(d->cursor_);
905 ErrorList & el = buffer_.errorList("Class Switch");
906 cap::switchBetweenClasses(
907 oldlayout, buffer_.params().documentClassPtr(),
908 static_cast<InsetText &>(buffer_.inset()), el);
910 setCursor(backcur.asDocIterator(&buffer_));
912 buffer_.errors("Class Switch");
913 buffer_.updateLabels();
917 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
919 Cursor & cur = d->cursor_;
921 switch (cmd.action) {
923 // FIXME: This is a bit problematic because we don't check is this is a
924 // document BufferView or not for these LFUNs. We probably have to
925 // dispatch both to currentBufferView() and, if that fails,
926 // to documentBufferView(); same as we do know for current Buffer and
927 // document Buffer. Ideally those LFUN should go to Buffer as they*
928 // operate on the full Buffer and the cursor is only needed either for
929 // an Undo record or to restore a cursor position. But we don't know
930 // how to do that inside Buffer of course.
931 case LFUN_BUFFER_PARAMS_APPLY:
932 case LFUN_LAYOUT_MODULES_CLEAR:
933 case LFUN_LAYOUT_MODULE_ADD:
934 case LFUN_LAYOUT_RELOAD:
935 case LFUN_TEXTCLASS_APPLY:
936 case LFUN_TEXTCLASS_LOAD:
937 flag.setEnabled(!buffer_.isReadonly());
941 flag.setEnabled(buffer_.undo().hasUndoStack());
944 flag.setEnabled(buffer_.undo().hasRedoStack());
946 case LFUN_FILE_INSERT:
947 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
948 case LFUN_FILE_INSERT_PLAINTEXT:
949 case LFUN_BOOKMARK_SAVE:
950 // FIXME: Actually, these LFUNS should be moved to Text
951 flag.setEnabled(cur.inTexted());
954 case LFUN_FONT_STATE:
955 case LFUN_LABEL_INSERT:
956 case LFUN_INFO_INSERT:
957 case LFUN_INSET_EDIT:
958 case LFUN_PARAGRAPH_GOTO:
960 case LFUN_REFERENCE_NEXT:
962 case LFUN_WORD_FIND_FORWARD:
963 case LFUN_WORD_FIND_BACKWARD:
964 case LFUN_WORD_FINDADV:
965 case LFUN_WORD_REPLACE:
968 case LFUN_MARK_TOGGLE:
969 case LFUN_SCREEN_RECENTER:
970 case LFUN_SCREEN_SHOW_CURSOR:
971 case LFUN_BIBTEX_DATABASE_ADD:
972 case LFUN_BIBTEX_DATABASE_DEL:
973 case LFUN_NOTES_MUTATE:
974 case LFUN_ALL_INSETS_TOGGLE:
975 case LFUN_STATISTICS:
976 case LFUN_BRANCH_ADD_INSERT:
977 case LFUN_KEYMAP_OFF:
978 case LFUN_KEYMAP_PRIMARY:
979 case LFUN_KEYMAP_SECONDARY:
980 case LFUN_KEYMAP_TOGGLE:
981 flag.setEnabled(true);
984 case LFUN_REGEXP_MODE:
985 // FIXME: Test if current WorkArea is the search WorkArea
986 flag.setEnabled(buffer().isInternal() && !cur.inRegexped());
989 case LFUN_LABEL_COPY_AS_REF: {
990 // if there is an inset at cursor, see whether it
992 Inset * inset = cur.nextInset();
993 if (!inset || !inset->getStatus(cur, cmd, flag))
994 flag.setEnabled(false);
998 case LFUN_NEXT_INSET_MODIFY: {
999 // this is the real function we want to invoke
1000 FuncRequest tmpcmd = cmd;
1001 tmpcmd.action = LFUN_INSET_MODIFY;
1002 // if there is an inset at cursor, see whether it
1003 // handles the lfun, other start from scratch
1004 Inset * inset = cur.nextInset();
1005 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
1006 flag = lyx::getStatus(tmpcmd);
1010 case LFUN_LABEL_GOTO: {
1011 flag.setEnabled(!cmd.argument().empty()
1012 || getInsetByCode<InsetRef>(cur, REF_CODE));
1016 case LFUN_CHANGES_TRACK:
1017 flag.setEnabled(true);
1018 flag.setOnOff(buffer_.params().trackChanges);
1021 case LFUN_CHANGES_OUTPUT:
1022 flag.setEnabled(true);
1023 flag.setOnOff(buffer_.params().outputChanges);
1026 case LFUN_CHANGES_MERGE:
1027 case LFUN_CHANGE_NEXT:
1028 case LFUN_CHANGE_PREVIOUS:
1029 case LFUN_ALL_CHANGES_ACCEPT:
1030 case LFUN_ALL_CHANGES_REJECT:
1031 // TODO: context-sensitive enabling of LFUNs
1032 // In principle, these command should only be enabled if there
1033 // is a change in the document. However, without proper
1034 // optimizations, this will inevitably result in poor performance.
1035 flag.setEnabled(true);
1038 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1039 flag.setOnOff(buffer_.params().compressed);
1043 case LFUN_SCREEN_UP:
1044 case LFUN_SCREEN_DOWN:
1046 case LFUN_SCREEN_UP_SELECT:
1047 case LFUN_SCREEN_DOWN_SELECT:
1048 flag.setEnabled(true);
1051 case LFUN_LAYOUT_TABULAR:
1052 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1056 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1059 case LFUN_LAYOUT_PARAGRAPH:
1060 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1063 case LFUN_DIALOG_SHOW_NEW_INSET:
1064 // FIXME: this is wrong, but I do not understand the
1066 if (cur.inset().lyxCode() == CAPTION_CODE)
1067 return cur.inset().getStatus(cur, cmd, flag);
1068 // FIXME we should consider passthru paragraphs too.
1069 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1073 flag.setEnabled(false);
1081 bool BufferView::dispatch(FuncRequest const & cmd)
1083 //lyxerr << [ cmd = " << cmd << "]" << endl;
1085 // Make sure that the cached BufferView is correct.
1086 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1087 << " arg[" << to_utf8(cmd.argument()) << ']'
1088 << " x[" << cmd.x << ']'
1089 << " y[" << cmd.y << ']'
1090 << " button[" << cmd.button() << ']');
1092 string const argument = to_utf8(cmd.argument());
1093 Cursor & cur = d->cursor_;
1095 switch (cmd.action) {
1097 case LFUN_BUFFER_PARAMS_APPLY: {
1098 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1099 cur.recordUndoFullDocument();
1100 istringstream ss(to_utf8(cmd.argument()));
1103 int const unknown_tokens = buffer_.readHeader(lex);
1104 if (unknown_tokens != 0) {
1105 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1106 << unknown_tokens << " unknown token"
1107 << (unknown_tokens == 1 ? "" : "s"));
1109 updateLayout(oldClass);
1111 // We are most certainly here because of a change in the document
1112 // It is then better to make sure that all dialogs are in sync with
1113 // current document settings.
1114 processUpdateFlags(Update::Force | Update::FitCursor);
1118 case LFUN_LAYOUT_MODULES_CLEAR: {
1119 DocumentClass const * const oldClass =
1120 buffer_.params().documentClassPtr();
1121 cur.recordUndoFullDocument();
1122 buffer_.params().clearLayoutModules();
1123 buffer_.params().makeDocumentClass();
1124 updateLayout(oldClass);
1125 processUpdateFlags(Update::Force | Update::FitCursor);
1129 case LFUN_LAYOUT_MODULE_ADD: {
1130 BufferParams const & params = buffer_.params();
1131 if (!params.moduleCanBeAdded(argument)) {
1132 LYXERR0("Module `" << argument <<
1133 "' cannot be added due to failed requirements or "
1134 "conflicts with installed modules.");
1137 DocumentClass const * const oldClass = params.documentClassPtr();
1138 cur.recordUndoFullDocument();
1139 buffer_.params().addLayoutModule(argument);
1140 buffer_.params().makeDocumentClass();
1141 updateLayout(oldClass);
1142 processUpdateFlags(Update::Force | Update::FitCursor);
1146 case LFUN_TEXTCLASS_APPLY: {
1147 if (!LayoutFileList::get().load(argument, buffer_.temppath()) &&
1148 !LayoutFileList::get().load(argument, buffer_.filePath()))
1151 LayoutFile const * old_layout = buffer_.params().baseClass();
1152 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1154 if (old_layout == new_layout)
1158 //Save the old, possibly modular, layout for use in conversion.
1159 DocumentClass const * const oldDocClass =
1160 buffer_.params().documentClassPtr();
1161 cur.recordUndoFullDocument();
1162 buffer_.params().setBaseClass(argument);
1163 buffer_.params().makeDocumentClass();
1164 updateLayout(oldDocClass);
1165 processUpdateFlags(Update::Force | Update::FitCursor);
1169 case LFUN_TEXTCLASS_LOAD:
1170 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1171 LayoutFileList::get().load(argument, buffer_.filePath());
1174 case LFUN_LAYOUT_RELOAD: {
1175 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1176 LayoutFileIndex bc = buffer_.params().baseClassID();
1177 LayoutFileList::get().reset(bc);
1178 buffer_.params().setBaseClass(bc);
1179 buffer_.params().makeDocumentClass();
1180 updateLayout(oldClass);
1181 processUpdateFlags(Update::Force | Update::FitCursor);
1186 cur.message(_("Undo"));
1187 cur.clearSelection();
1188 if (!cur.textUndo())
1189 cur.message(_("No further undo information"));
1191 processUpdateFlags(Update::Force | Update::FitCursor);
1195 cur.message(_("Redo"));
1196 cur.clearSelection();
1197 if (!cur.textRedo())
1198 cur.message(_("No further redo information"));
1200 processUpdateFlags(Update::Force | Update::FitCursor);
1203 case LFUN_FONT_STATE:
1204 cur.message(cur.currentState());
1207 case LFUN_BOOKMARK_SAVE:
1208 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1211 case LFUN_LABEL_GOTO: {
1212 docstring label = cmd.argument();
1213 if (label.empty()) {
1215 getInsetByCode<InsetRef>(cur, REF_CODE);
1217 label = inset->getParam("reference");
1218 // persistent=false: use temp_bookmark
1227 case LFUN_INSET_EDIT: {
1228 FuncRequest fr(cmd);
1229 // if there is an inset at cursor, see whether it
1231 Inset * inset = cur.nextInset();
1233 inset->dispatch(cur, fr);
1234 // if it did not work, try the underlying inset.
1235 if (!inset || !cur.result().dispatched())
1238 // FIXME I'm adding the last break to solve a crash,
1239 // but that is obviously not right.
1240 if (!cur.result().dispatched())
1241 // It did not work too; no action needed.
1246 case LFUN_PARAGRAPH_GOTO: {
1247 int const id = convert<int>(cmd.getArg(0));
1248 int const pos = convert<int>(cmd.getArg(1));
1250 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1251 b = theBufferList().next(b)) {
1253 DocIterator dit = b->getParFromID(id);
1255 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1259 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1260 << " found in buffer `"
1261 << b->absFileName() << "'.");
1263 if (b == &buffer_) {
1267 processUpdateFlags(Update::Force | Update::FitCursor);
1269 // Switch to other buffer view and resend cmd
1270 theLyXFunc().dispatch(FuncRequest(
1271 LFUN_BUFFER_SWITCH, b->absFileName()));
1272 theLyXFunc().dispatch(cmd);
1279 case LFUN_NOTE_NEXT:
1280 gotoInset(this, NOTE_CODE, false);
1283 case LFUN_REFERENCE_NEXT: {
1284 vector<InsetCode> tmp;
1285 tmp.push_back(LABEL_CODE);
1286 tmp.push_back(REF_CODE);
1287 gotoInset(this, tmp, true);
1291 case LFUN_CHANGES_TRACK:
1292 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1295 case LFUN_CHANGES_OUTPUT:
1296 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1297 if (buffer_.params().outputChanges) {
1298 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1299 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1300 LaTeXFeatures::isAvailable("xcolor");
1302 if (!dvipost && !xcolorulem) {
1303 Alert::warning(_("Changes not shown in LaTeX output"),
1304 _("Changes will not be highlighted in LaTeX output, "
1305 "because neither dvipost nor xcolor/ulem are installed.\n"
1306 "Please install these packages or redefine "
1307 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1308 } else if (!xcolorulem) {
1309 Alert::warning(_("Changes not shown in LaTeX output"),
1310 _("Changes will not be highlighted in LaTeX output "
1311 "when using pdflatex, because xcolor and ulem are not installed.\n"
1312 "Please install both packages or redefine "
1313 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1318 case LFUN_CHANGE_NEXT:
1319 findNextChange(this);
1320 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1321 processUpdateFlags(Update::Force | Update::FitCursor);
1324 case LFUN_CHANGE_PREVIOUS:
1325 findPreviousChange(this);
1326 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1327 processUpdateFlags(Update::Force | Update::FitCursor);
1330 case LFUN_CHANGES_MERGE:
1331 if (findNextChange(this) || findPreviousChange(this)) {
1332 processUpdateFlags(Update::Force | Update::FitCursor);
1333 showDialog("changes");
1337 case LFUN_ALL_CHANGES_ACCEPT:
1338 // select complete document
1339 cur.reset(buffer_.inset());
1340 cur.selHandle(true);
1341 buffer_.text().cursorBottom(cur);
1342 // accept everything in a single step to support atomic undo
1343 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1344 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1345 processUpdateFlags(Update::Force | Update::FitCursor);
1348 case LFUN_ALL_CHANGES_REJECT:
1349 // select complete document
1350 cur.reset(buffer_.inset());
1351 cur.selHandle(true);
1352 buffer_.text().cursorBottom(cur);
1353 // reject everything in a single step to support atomic undo
1354 // Note: reject does not work recursively; the user may have to repeat the operation
1355 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1356 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1357 processUpdateFlags(Update::Force | Update::FitCursor);
1360 case LFUN_WORD_FIND_FORWARD:
1361 case LFUN_WORD_FIND_BACKWARD: {
1362 static docstring last_search;
1363 docstring searched_string;
1365 if (!cmd.argument().empty()) {
1366 last_search = cmd.argument();
1367 searched_string = cmd.argument();
1369 searched_string = last_search;
1372 if (searched_string.empty())
1375 bool const fw = cmd.action == LFUN_WORD_FIND_FORWARD;
1376 docstring const data =
1377 find2string(searched_string, true, false, fw);
1378 find(this, FuncRequest(LFUN_WORD_FIND, data));
1382 case LFUN_WORD_FIND: {
1383 FuncRequest req = cmd;
1384 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1385 req = d->search_request_cache_;
1386 if (req.argument().empty()) {
1387 theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1390 if (find(this, req))
1393 message(_("String not found!"));
1394 d->search_request_cache_ = req;
1398 case LFUN_WORD_REPLACE: {
1399 bool has_deleted = false;
1400 if (cur.selection()) {
1401 DocIterator beg = cur.selectionBegin();
1402 DocIterator end = cur.selectionEnd();
1403 if (beg.pit() == end.pit()) {
1404 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1405 if (cur.paragraph().isDeleted(p))
1410 replace(this, cmd, has_deleted);
1414 case LFUN_WORD_FINDADV:
1419 cur.clearSelection();
1420 cur.message(from_utf8(N_("Mark off")));
1424 cur.clearSelection();
1426 cur.message(from_utf8(N_("Mark on")));
1429 case LFUN_MARK_TOGGLE:
1430 cur.setSelection(false);
1433 cur.message(from_utf8(N_("Mark removed")));
1436 cur.message(from_utf8(N_("Mark set")));
1441 case LFUN_SCREEN_SHOW_CURSOR:
1445 case LFUN_SCREEN_RECENTER:
1449 case LFUN_BIBTEX_DATABASE_ADD: {
1450 Cursor tmpcur = cur;
1451 findInset(tmpcur, BIBTEX_CODE, false);
1452 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1455 if (inset->addDatabase(cmd.argument()))
1456 buffer_.updateBibfilesCache();
1461 case LFUN_BIBTEX_DATABASE_DEL: {
1462 Cursor tmpcur = cur;
1463 findInset(tmpcur, BIBTEX_CODE, false);
1464 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1467 if (inset->delDatabase(cmd.argument()))
1468 buffer_.updateBibfilesCache();
1473 case LFUN_STATISTICS: {
1474 DocIterator from, to;
1475 if (cur.selection()) {
1476 from = cur.selectionBegin();
1477 to = cur.selectionEnd();
1479 from = doc_iterator_begin(&buffer_);
1480 to = doc_iterator_end(&buffer_);
1482 int const words = countWords(from, to);
1483 int const chars = countChars(from, to, false);
1484 int const chars_blanks = countChars(from, to, true);
1486 if (cur.selection())
1487 message = _("Statistics for the selection:");
1489 message = _("Statistics for the document:");
1492 message += bformat(_("%1$d words"), words);
1494 message += _("One word");
1496 if (chars_blanks != 1)
1497 message += bformat(_("%1$d characters (including blanks)"),
1500 message += _("One character (including blanks)");
1503 message += bformat(_("%1$d characters (excluding blanks)"),
1506 message += _("One character (excluding blanks)");
1508 Alert::information(_("Statistics"), message);
1512 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1513 // turn compression on/off
1514 buffer_.params().compressed = !buffer_.params().compressed;
1517 case LFUN_LABEL_COPY_AS_REF: {
1518 // if there is an inset at cursor, try to copy it
1519 Inset * inset = &cur.inset();
1520 if (!inset || !inset->asInsetMath())
1521 inset = cur.nextInset();
1523 FuncRequest tmpcmd = cmd;
1524 inset->dispatch(cur, tmpcmd);
1526 if (!cur.result().dispatched())
1527 // It did not work too; no action needed.
1529 cur.clearSelection();
1530 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1534 case LFUN_NEXT_INSET_MODIFY: {
1535 // create the the real function we want to invoke
1536 FuncRequest tmpcmd = cmd;
1537 tmpcmd.action = LFUN_INSET_MODIFY;
1538 // if there is an inset at cursor, see whether it
1540 Inset * inset = cur.nextInset();
1543 inset->dispatch(cur, tmpcmd);
1545 // if it did not work, try the underlying inset.
1546 if (!inset || !cur.result().dispatched()) {
1548 cur.dispatch(tmpcmd);
1551 if (!cur.result().dispatched())
1552 // It did not work too; no action needed.
1554 cur.clearSelection();
1555 processUpdateFlags(Update::Force | Update::FitCursor);
1559 case LFUN_SCREEN_UP:
1560 case LFUN_SCREEN_DOWN: {
1561 Point p = getPos(cur, cur.boundary());
1562 // This code has been commented out to enable to scroll down a
1563 // document, even if there are large insets in it (see bug #5465).
1564 /*if (p.y_ < 0 || p.y_ > height_) {
1565 // The cursor is off-screen so recenter before proceeding.
1567 p = getPos(cur, cur.boundary());
1569 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1570 ? -height_ : height_);
1571 if (cmd.action == LFUN_SCREEN_UP && scrolled > -height_)
1573 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1574 p = Point(width_, height_);
1576 bool const in_texted = cur.inTexted();
1577 cur.reset(buffer_.inset());
1580 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1581 true, cmd.action == LFUN_SCREEN_UP);
1582 //FIXME: what to do with cur.x_target()?
1583 bool update = in_texted && cur.bv().checkDepm(cur, old);
1586 processUpdateFlags(Update::Force | Update::FitCursor);
1594 case LFUN_SCREEN_UP_SELECT: {
1595 cur.selHandle(true);
1596 if (isTopScreen()) {
1597 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1601 int y = getPos(cur, cur.boundary()).y_;
1602 int const ymin = y - height_ + defaultRowHeight();
1603 while (y > ymin && cur.up())
1604 y = getPos(cur, cur.boundary()).y_;
1607 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1611 case LFUN_SCREEN_DOWN_SELECT: {
1612 cur.selHandle(true);
1613 if (isBottomScreen()) {
1614 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1618 int y = getPos(cur, cur.boundary()).y_;
1619 int const ymax = y + height_ - defaultRowHeight();
1620 while (y < ymax && cur.down())
1621 y = getPos(cur, cur.boundary()).y_;
1624 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1628 // This could be rewriten using some command like forall <insetname> <command>
1629 // once the insets refactoring is done.
1630 case LFUN_NOTES_MUTATE: {
1631 if (cmd.argument().empty())
1634 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1635 processUpdateFlags(Update::Force);
1640 case LFUN_ALL_INSETS_TOGGLE: {
1642 string const name = split(to_utf8(cmd.argument()), action, ' ');
1643 InsetCode const inset_code = insetCode(name);
1645 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1647 Inset & inset = cur.buffer()->inset();
1648 InsetIterator it = inset_iterator_begin(inset);
1649 InsetIterator const end = inset_iterator_end(inset);
1650 for (; it != end; ++it) {
1651 if (it->asInsetCollapsable()
1652 && (inset_code == NO_CODE
1653 || inset_code == it->lyxCode())) {
1654 Cursor tmpcur = cur;
1655 tmpcur.pushBackward(*it);
1656 it->dispatch(tmpcur, fr);
1659 processUpdateFlags(Update::Force | Update::FitCursor);
1663 case LFUN_BRANCH_ADD_INSERT: {
1664 docstring branch_name = from_utf8(cmd.getArg(0));
1665 if (branch_name.empty())
1666 if (!Alert::askForText(branch_name, _("Branch name")) ||
1667 branch_name.empty())
1670 DispatchResult drtmp;
1671 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1672 if (drtmp.error()) {
1673 Alert::warning(_("Branch already exists"), drtmp.message());
1676 BranchList & branch_list = buffer_.params().branchlist();
1677 Branch const * branch = branch_list.find(branch_name);
1678 string const x11hexname = X11hexname(branch->color());
1679 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1680 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1681 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1685 case LFUN_KEYMAP_OFF:
1686 getIntl().keyMapOn(false);
1689 case LFUN_KEYMAP_PRIMARY:
1690 getIntl().keyMapPrim();
1693 case LFUN_KEYMAP_SECONDARY:
1694 getIntl().keyMapSec();
1697 case LFUN_KEYMAP_TOGGLE:
1698 getIntl().toggleKeyMap();
1709 docstring const BufferView::requestSelection()
1711 Cursor & cur = d->cursor_;
1713 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1714 if (!cur.selection()) {
1715 d->xsel_cache_.set = false;
1719 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1720 if (!d->xsel_cache_.set ||
1721 cur.top() != d->xsel_cache_.cursor ||
1722 cur.anchor_.top() != d->xsel_cache_.anchor)
1724 d->xsel_cache_.cursor = cur.top();
1725 d->xsel_cache_.anchor = cur.anchor_.top();
1726 d->xsel_cache_.set = cur.selection();
1727 return cur.selectionAsString(false);
1733 void BufferView::clearSelection()
1735 d->cursor_.clearSelection();
1736 // Clear the selection buffer. Otherwise a subsequent
1737 // middle-mouse-button paste would use the selection buffer,
1738 // not the more current external selection.
1739 cap::clearSelection();
1740 d->xsel_cache_.set = false;
1741 // The buffer did not really change, but this causes the
1742 // redraw we need because we cleared the selection above.
1747 void BufferView::resize(int width, int height)
1749 // Update from work area
1753 // Clear the paragraph height cache.
1754 d->par_height_.clear();
1755 // Redo the metrics.
1760 Inset const * BufferView::getCoveringInset(Text const & text,
1763 TextMetrics & tm = d->text_metrics_[&text];
1764 Inset * inset = tm.checkInsetHit(x, y);
1768 if (!inset->descendable())
1769 // No need to go further down if the inset is not
1773 size_t cell_number = inset->nargs();
1774 // Check all the inner cell.
1775 for (size_t i = 0; i != cell_number; ++i) {
1776 Text const * inner_text = inset->getText(i);
1779 Inset const * inset_deeper =
1780 getCoveringInset(*inner_text, x, y);
1782 return inset_deeper;
1790 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1792 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1794 // This is only called for mouse related events including
1795 // LFUN_FILE_OPEN generated by drag-and-drop.
1796 FuncRequest cmd = cmd0;
1798 Cursor old = cursor();
1800 cur.push(buffer_.inset());
1801 cur.setSelection(d->cursor_.selection());
1803 // Either the inset under the cursor or the
1804 // surrounding Text will handle this event.
1806 // make sure we stay within the screen...
1807 cmd.y = min(max(cmd.y, -1), height_);
1809 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1811 // Get inset under mouse, if there is one.
1812 Inset const * covering_inset =
1813 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1814 if (covering_inset == d->last_inset_)
1815 // Same inset, no need to do anything...
1818 bool need_redraw = false;
1819 // const_cast because of setMouseHover().
1820 Inset * inset = const_cast<Inset *>(covering_inset);
1822 // Remove the hint on the last hovered inset (if any).
1823 need_redraw |= d->last_inset_->setMouseHover(false);
1825 // Highlighted the newly hovered inset (if any).
1826 need_redraw |= inset->setMouseHover(true);
1827 d->last_inset_ = inset;
1831 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1832 << cmd.x << ", " << cmd.y << ")");
1834 d->update_strategy_ = DecorationUpdate;
1836 // This event (moving without mouse click) is not passed further.
1837 // This should be changed if it is further utilized.
1842 // Build temporary cursor.
1843 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1845 // Put anchor at the same position.
1848 cur.beginUndoGroup();
1850 // Try to dispatch to an non-editable inset near this position
1851 // via the temp cursor. If the inset wishes to change the real
1852 // cursor it has to do so explicitly by using
1853 // cur.bv().cursor() = cur; (or similar)
1855 inset->dispatch(cur, cmd);
1857 // Now dispatch to the temporary cursor. If the real cursor should
1858 // be modified, the inset's dispatch has to do so explicitly.
1859 if (!inset || !cur.result().dispatched())
1864 // Notify left insets
1867 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
1869 cursor().fixIfBroken();
1872 // Do we have a selection?
1873 theSelection().haveSelection(cursor().selection());
1875 // If the command has been dispatched,
1876 if (cur.result().dispatched() || cur.result().update())
1877 processUpdateFlags(cur.result().update());
1881 void BufferView::lfunScroll(FuncRequest const & cmd)
1883 string const scroll_type = cmd.getArg(0);
1884 int const scroll_step =
1885 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1886 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1887 if (scroll_step == 0)
1889 string const scroll_quantity = cmd.getArg(1);
1890 if (scroll_quantity == "up")
1891 scrollUp(scroll_step);
1892 else if (scroll_quantity == "down")
1893 scrollDown(scroll_step);
1895 int const scroll_value = convert<int>(scroll_quantity);
1897 scroll(scroll_step * scroll_value);
1904 int BufferView::minVisiblePart()
1906 return 2 * defaultRowHeight();
1910 int BufferView::scroll(int y)
1913 return scrollDown(y);
1915 return scrollUp(-y);
1920 int BufferView::scrollDown(int offset)
1922 Text * text = &buffer_.text();
1923 TextMetrics & tm = d->text_metrics_[text];
1924 int const ymax = height_ + offset;
1926 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1927 int bottom_pos = last.second->position() + last.second->descent();
1928 if (lyxrc.scroll_below_document)
1929 bottom_pos += height_ - minVisiblePart();
1930 if (last.first + 1 == int(text->paragraphs().size())) {
1931 if (bottom_pos <= height_)
1933 offset = min(offset, bottom_pos - height_);
1936 if (bottom_pos > ymax)
1938 tm.newParMetricsDown();
1940 d->anchor_ypos_ -= offset;
1945 int BufferView::scrollUp(int offset)
1947 Text * text = &buffer_.text();
1948 TextMetrics & tm = d->text_metrics_[text];
1949 int ymin = - offset;
1951 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1952 int top_pos = first.second->position() - first.second->ascent();
1953 if (first.first == 0) {
1956 offset = min(offset, - top_pos);
1961 tm.newParMetricsUp();
1963 d->anchor_ypos_ += offset;
1968 void BufferView::setCursorFromRow(int row)
1973 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1975 d->cursor_.reset(buffer_.inset());
1977 buffer_.text().setCursor(d->cursor_, 0, 0);
1979 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1983 bool BufferView::setCursorFromInset(Inset const * inset)
1985 // are we already there?
1986 if (cursor().nextInset() == inset)
1989 // Inset is not at cursor position. Find it in the document.
1991 cur.reset(buffer().inset());
1992 while (cur && cur.nextInset() != inset)
2003 void BufferView::gotoLabel(docstring const & label)
2005 std::vector<Buffer const *> bufs = buffer().allRelatives();
2006 std::vector<Buffer const *>::iterator it = bufs.begin();
2007 for (; it != bufs.end(); ++it) {
2008 Buffer const * buf = *it;
2011 Toc & toc = buf->tocBackend().toc("label");
2012 TocIterator toc_it = toc.begin();
2013 TocIterator end = toc.end();
2014 for (; toc_it != end; ++toc_it) {
2015 if (label == toc_it->str()) {
2016 dispatch(toc_it->action());
2024 TextMetrics const & BufferView::textMetrics(Text const * t) const
2026 return const_cast<BufferView *>(this)->textMetrics(t);
2030 TextMetrics & BufferView::textMetrics(Text const * t)
2032 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2033 if (tmc_it == d->text_metrics_.end()) {
2034 tmc_it = d->text_metrics_.insert(
2035 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2037 return tmc_it->second;
2041 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2044 return textMetrics(t).parMetrics(pit);
2048 int BufferView::workHeight() const
2054 void BufferView::setCursor(DocIterator const & dit)
2056 d->cursor_.reset(buffer().inset());
2057 size_t const n = dit.depth();
2058 for (size_t i = 0; i < n; ++i)
2059 dit[i].inset().edit(d->cursor_, true);
2061 d->cursor_.setCursor(dit);
2062 d->cursor_.setSelection(false);
2066 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2068 // Would be wrong to delete anything if we have a selection.
2069 if (cur.selection())
2072 bool need_anchor_change = false;
2073 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2074 need_anchor_change);
2076 if (need_anchor_change)
2084 buffer_.updateLabels();
2092 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2094 LASSERT(&cur.bv() == this, /**/);
2097 // this event will clear selection so we save selection for
2098 // persistent selection
2099 cap::saveSelection(cursor());
2101 // Has the cursor just left the inset?
2102 bool leftinset = (&d->cursor_.inset() != &cur.inset());
2104 d->cursor_.fixIfBroken();
2106 // FIXME: shift-mouse selection doesn't work well across insets.
2107 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
2109 // do the dEPM magic if needed
2110 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2111 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2112 // the leftinset bool would not be necessary (badcursor instead).
2113 bool update = leftinset;
2114 if (!do_selection && d->cursor_.inTexted())
2115 update |= checkDepm(cur, d->cursor_);
2116 d->cursor_.macroModeClose();
2118 d->cursor_.resetAnchor();
2119 d->cursor_.setCursor(cur);
2120 d->cursor_.boundary(cur.boundary());
2122 d->cursor_.setSelection();
2124 d->cursor_.clearSelection();
2126 d->cursor_.finishUndo();
2127 d->cursor_.setCurrentFont();
2132 void BufferView::putSelectionAt(DocIterator const & cur,
2133 int length, bool backwards)
2135 d->cursor_.clearSelection();
2141 d->cursor_.pos() += length;
2142 d->cursor_.setSelection(d->cursor_, -length);
2144 d->cursor_.setSelection(d->cursor_, length);
2146 // Ensure a redraw happens in any case because the new selection could
2147 // possibly be on the same screen as the previous selection.
2148 processUpdateFlags(Update::Force | Update::FitCursor);
2152 Cursor & BufferView::cursor()
2158 Cursor const & BufferView::cursor() const
2164 pit_type BufferView::anchor_ref() const
2166 return d->anchor_pit_;
2170 bool BufferView::singleParUpdate()
2172 Text & buftext = buffer_.text();
2173 pit_type const bottom_pit = d->cursor_.bottom().pit();
2174 TextMetrics & tm = textMetrics(&buftext);
2175 int old_height = tm.parMetrics(bottom_pit).height();
2177 // make sure inline completion pointer is ok
2178 if (d->inlineCompletionPos_.fixIfBroken())
2179 d->inlineCompletionPos_ = DocIterator();
2181 // In Single Paragraph mode, rebreak only
2182 // the (main text, not inset!) paragraph containing the cursor.
2183 // (if this paragraph contains insets etc., rebreaking will
2184 // recursively descend)
2185 tm.redoParagraph(bottom_pit);
2186 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2187 if (pm.height() != old_height)
2188 // Paragraph height has changed so we cannot proceed to
2189 // the singlePar optimisation.
2192 d->update_strategy_ = SingleParUpdate;
2194 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2195 << " y2: " << pm.position() + pm.descent()
2196 << " pit: " << bottom_pit
2197 << " singlepar: 1");
2202 void BufferView::updateMetrics()
2204 if (height_ == 0 || width_ == 0)
2207 Text & buftext = buffer_.text();
2208 pit_type const npit = int(buftext.paragraphs().size());
2210 // Clear out the position cache in case of full screen redraw,
2211 d->coord_cache_.clear();
2213 // Clear out paragraph metrics to avoid having invalid metrics
2214 // in the cache from paragraphs not relayouted below
2215 // The complete text metrics will be redone.
2216 d->text_metrics_.clear();
2218 TextMetrics & tm = textMetrics(&buftext);
2220 // make sure inline completion pointer is ok
2221 if (d->inlineCompletionPos_.fixIfBroken())
2222 d->inlineCompletionPos_ = DocIterator();
2224 if (d->anchor_pit_ >= npit)
2225 // The anchor pit must have been deleted...
2226 d->anchor_pit_ = npit - 1;
2228 // Rebreak anchor paragraph.
2229 tm.redoParagraph(d->anchor_pit_);
2230 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2233 if (d->anchor_pit_ == 0) {
2234 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2236 // Complete buffer visible? Then it's easy.
2237 if (scrollRange == 0)
2238 d->anchor_ypos_ = anchor_pm.ascent();
2240 // FIXME: Some clever handling needed to show
2241 // the _first_ paragraph up to the top if the cursor is
2242 // in the first line.
2244 anchor_pm.setPosition(d->anchor_ypos_);
2246 LYXERR(Debug::PAINTING, "metrics: "
2247 << " anchor pit = " << d->anchor_pit_
2248 << " anchor ypos = " << d->anchor_ypos_);
2250 // Redo paragraphs above anchor if necessary.
2251 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2252 // We are now just above the anchor paragraph.
2253 pit_type pit1 = d->anchor_pit_ - 1;
2254 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2255 tm.redoParagraph(pit1);
2256 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2258 // Save the paragraph position in the cache.
2263 // Redo paragraphs below the anchor if necessary.
2264 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2265 // We are now just below the anchor paragraph.
2266 pit_type pit2 = d->anchor_pit_ + 1;
2267 for (; pit2 < npit && y2 <= height_; ++pit2) {
2268 tm.redoParagraph(pit2);
2269 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2271 // Save the paragraph position in the cache.
2276 LYXERR(Debug::PAINTING, "Metrics: "
2277 << " anchor pit = " << d->anchor_pit_
2278 << " anchor ypos = " << d->anchor_ypos_
2281 << " pit1 = " << pit1
2282 << " pit2 = " << pit2);
2284 d->update_strategy_ = FullScreenUpdate;
2286 if (lyxerr.debugging(Debug::WORKAREA)) {
2287 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2288 d->coord_cache_.dump();
2293 void BufferView::insertLyXFile(FileName const & fname)
2295 LASSERT(d->cursor_.inTexted(), /**/);
2297 // Get absolute path of file and add ".lyx"
2298 // to the filename if necessary
2299 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2301 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2302 // emit message signal.
2303 message(bformat(_("Inserting document %1$s..."), disp_fn));
2306 Buffer buf("", false);
2307 if (buf.loadLyXFile(filename)) {
2308 ErrorList & el = buffer_.errorList("Parse");
2309 // Copy the inserted document error list into the current buffer one.
2310 el = buf.errorList("Parse");
2311 buffer_.undo().recordUndo(d->cursor_);
2312 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2313 buf.params().documentClassPtr(), el);
2314 res = _("Document %1$s inserted.");
2316 res = _("Could not insert document %1$s");
2321 // emit message signal.
2322 message(bformat(res, disp_fn));
2323 buffer_.errors("Parse");
2327 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2333 // Addup contribution of nested insets, from inside to outside,
2334 // keeping the outer paragraph for a special handling below
2335 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2336 CursorSlice const & sl = dit[i];
2340 // get relative position inside sl.inset()
2341 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2343 // Make relative position inside of the edited inset relative to sl.inset()
2347 // In case of an RTL inset, the edited inset will be positioned to the left
2350 bool boundary_i = boundary && i + 1 == dit.depth();
2351 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2356 // remember width for the case that sl.inset() is positioned in an RTL inset
2357 if (i && dit[i - 1].text()) {
2358 // If this Inset is inside a Text Inset, retrieve the Dimension
2359 // from the containing text instead of using Inset::dimension() which
2360 // might not be implemented.
2361 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2362 // elimination of Inset::dim_ cache. This coordOffset() method needs
2363 // to be rewritten in light of the new design.
2364 Dimension const & dim = parMetrics(dit[i - 1].text(),
2365 dit[i - 1].pit()).insetDimension(&sl.inset());
2368 Dimension const dim = sl.inset().dimension(*this);
2372 //lyxerr << "Cursor::getPos, i: "
2373 // << i << " x: " << xx << " y: " << y << endl;
2376 // Add contribution of initial rows of outermost paragraph
2377 CursorSlice const & sl = dit[0];
2378 TextMetrics const & tm = textMetrics(sl.text());
2379 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2380 LASSERT(!pm.rows().empty(), /**/);
2381 y -= pm.rows()[0].ascent();
2383 // FIXME: document this mess
2385 if (sl.pos() > 0 && dit.depth() == 1) {
2387 if (pos && boundary)
2389 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2390 rend = pm.pos2row(pos);
2392 rend = pm.pos2row(sl.pos());
2394 size_t rend = pm.pos2row(sl.pos());
2396 for (size_t rit = 0; rit != rend; ++rit)
2397 y += pm.rows()[rit].height();
2398 y += pm.rows()[rend].ascent();
2400 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2402 // Make relative position from the nested inset now bufferview absolute.
2403 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2406 // In the RTL case place the nested inset at the left of the cursor in
2407 // the outer paragraph
2408 bool boundary_1 = boundary && 1 == dit.depth();
2409 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2417 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2419 if (!paragraphVisible(dit))
2420 return Point(-1, -1);
2422 CursorSlice const & bot = dit.bottom();
2423 TextMetrics const & tm = textMetrics(bot.text());
2425 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2426 p.y_ += tm.parMetrics(bot.pit()).position();
2431 bool BufferView::paragraphVisible(DocIterator const & dit) const
2433 CursorSlice const & bot = dit.bottom();
2434 TextMetrics const & tm = textMetrics(bot.text());
2436 return tm.contains(bot.pit());
2440 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2442 Cursor const & cur = cursor();
2443 Font const font = cur.getFont();
2444 frontend::FontMetrics const & fm = theFontMetrics(font);
2445 int const asc = fm.maxAscent();
2446 int const des = fm.maxDescent();
2448 p = getPos(cur, cur.boundary());
2453 bool BufferView::cursorInView(Point const & p, int h) const
2455 Cursor const & cur = cursor();
2456 // does the cursor touch the screen ?
2457 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2463 void BufferView::draw(frontend::Painter & pain)
2465 if (height_ == 0 || width_ == 0)
2467 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2469 Text & text = buffer_.text();
2470 TextMetrics const & tm = d->text_metrics_[&text];
2471 int const y = tm.first().second->position();
2472 PainterInfo pi(this, pain);
2474 switch (d->update_strategy_) {
2476 case NoScreenUpdate:
2477 // If no screen painting is actually needed, only some the different
2478 // coordinates of insets and paragraphs needs to be updated.
2479 pi.full_repaint = true;
2480 pi.pain.setDrawingEnabled(false);
2484 case SingleParUpdate:
2485 pi.full_repaint = false;
2486 // In general, only the current row of the outermost paragraph
2487 // will be redrawn. Particular cases where selection spans
2488 // multiple paragraph are correctly detected in TextMetrics.
2492 case DecorationUpdate:
2493 // FIXME: We should also distinguish DecorationUpdate to avoid text
2494 // drawing if possible. This is not possible to do easily right now
2495 // because of the single backing pixmap.
2497 case FullScreenUpdate:
2498 // The whole screen, including insets, will be refreshed.
2499 pi.full_repaint = true;
2501 // Clear background.
2502 pain.fillRectangle(0, 0, width_, height_,
2503 pi.backgroundColor(&buffer_.inset()));
2508 // and possibly grey out below
2509 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2510 int const y2 = lastpm.second->position() + lastpm.second->descent();
2513 Color color = buffer().isInternal()
2514 ? Color_background : Color_bottomarea;
2515 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2519 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2521 // The scrollbar needs an update.
2524 // Normalize anchor for next time
2525 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2526 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2527 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2528 ParagraphMetrics const & pm = tm.parMetrics(pit);
2529 if (pm.position() + pm.descent() > 0) {
2530 d->anchor_pit_ = pit;
2531 d->anchor_ypos_ = pm.position();
2535 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2536 << " anchor ypos = " << d->anchor_ypos_);
2540 void BufferView::message(docstring const & msg)
2543 d->gui_->message(msg);
2547 void BufferView::showDialog(string const & name)
2550 d->gui_->showDialog(name, string());
2554 void BufferView::showDialog(string const & name,
2555 string const & data, Inset * inset)
2558 d->gui_->showDialog(name, data, inset);
2562 void BufferView::updateDialog(string const & name, string const & data)
2565 d->gui_->updateDialog(name, data);
2569 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2575 // FIXME: Move this out of BufferView again
2576 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2578 if (!fname.isReadableFile()) {
2579 docstring const error = from_ascii(strerror(errno));
2580 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2581 docstring const text =
2582 bformat(_("Could not read the specified document\n"
2583 "%1$s\ndue to the error: %2$s"), file, error);
2584 Alert::error(_("Could not read file"), text);
2588 if (!fname.isReadableFile()) {
2589 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2590 docstring const text =
2591 bformat(_("%1$s\n is not readable."), file);
2592 Alert::error(_("Could not open file"), text);
2596 // FIXME UNICODE: We don't know the encoding of the file
2597 docstring file_content = fname.fileContents("UTF-8");
2598 if (file_content.empty()) {
2599 Alert::error(_("Reading not UTF-8 encoded file"),
2600 _("The file is not UTF-8 encoded.\n"
2601 "It will be read as local 8Bit-encoded.\n"
2602 "If this does not give the correct result\n"
2603 "then please change the encoding of the file\n"
2604 "to UTF-8 with a program other than LyX.\n"));
2605 file_content = fname.fileContents("local8bit");
2608 return normalize_c(file_content);
2612 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2614 docstring const tmpstr = contentsOfPlaintextFile(f);
2619 Cursor & cur = cursor();
2620 cap::replaceSelection(cur);
2621 buffer_.undo().recordUndo(cur);
2623 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2625 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2632 docstring const & BufferView::inlineCompletion() const
2634 return d->inlineCompletion_;
2638 size_t const & BufferView::inlineCompletionUniqueChars() const
2640 return d->inlineCompletionUniqueChars_;
2644 DocIterator const & BufferView::inlineCompletionPos() const
2646 return d->inlineCompletionPos_;
2650 bool samePar(DocIterator const & a, DocIterator const & b)
2652 if (a.empty() && b.empty())
2654 if (a.empty() || b.empty())
2656 if (a.depth() != b.depth())
2658 return &a.innerParagraph() == &b.innerParagraph();
2662 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2663 docstring const & completion, size_t uniqueChars)
2665 uniqueChars = min(completion.size(), uniqueChars);
2666 bool changed = d->inlineCompletion_ != completion
2667 || d->inlineCompletionUniqueChars_ != uniqueChars;
2668 bool singlePar = true;
2669 d->inlineCompletion_ = completion;
2670 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2672 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2675 DocIterator const & old = d->inlineCompletionPos_;
2677 //lyxerr << "inlineCompletionPos changed" << std::endl;
2678 // old or pos are in another paragraph?
2679 if ((!samePar(cur, pos) && !pos.empty())
2680 || (!samePar(cur, old) && !old.empty())) {
2682 //lyxerr << "different paragraph" << std::endl;
2684 d->inlineCompletionPos_ = pos;
2689 if (singlePar && !(cur.disp_.update() & Update::Force))
2690 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2692 cur.updateFlags(cur.disp_.update() | Update::Force);