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 if (buffer_.isInternal())
1100 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1101 cur.recordUndoFullDocument();
1102 istringstream ss(to_utf8(cmd.argument()));
1105 int const unknown_tokens = buffer_.readHeader(lex);
1106 if (unknown_tokens != 0) {
1107 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1108 << unknown_tokens << " unknown token"
1109 << (unknown_tokens == 1 ? "" : "s"));
1111 updateLayout(oldClass);
1113 // We are most certainly here because of a change in the document
1114 // It is then better to make sure that all dialogs are in sync with
1115 // current document settings.
1116 processUpdateFlags(Update::Force | Update::FitCursor);
1120 case LFUN_LAYOUT_MODULES_CLEAR: {
1121 if (buffer_.isInternal())
1123 DocumentClass const * const oldClass =
1124 buffer_.params().documentClassPtr();
1125 cur.recordUndoFullDocument();
1126 buffer_.params().clearLayoutModules();
1127 buffer_.params().makeDocumentClass();
1128 updateLayout(oldClass);
1129 processUpdateFlags(Update::Force | Update::FitCursor);
1133 case LFUN_LAYOUT_MODULE_ADD: {
1134 if (buffer_.isInternal())
1136 BufferParams const & params = buffer_.params();
1137 if (!params.moduleCanBeAdded(argument)) {
1138 LYXERR0("Module `" << argument <<
1139 "' cannot be added due to failed requirements or "
1140 "conflicts with installed modules.");
1143 DocumentClass const * const oldClass = params.documentClassPtr();
1144 cur.recordUndoFullDocument();
1145 buffer_.params().addLayoutModule(argument);
1146 buffer_.params().makeDocumentClass();
1147 updateLayout(oldClass);
1148 processUpdateFlags(Update::Force | Update::FitCursor);
1152 case LFUN_TEXTCLASS_APPLY: {
1153 if (buffer_.isInternal())
1155 if (!LayoutFileList::get().load(argument, buffer_.temppath()) &&
1156 !LayoutFileList::get().load(argument, buffer_.filePath()))
1159 LayoutFile const * old_layout = buffer_.params().baseClass();
1160 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1162 if (old_layout == new_layout)
1166 //Save the old, possibly modular, layout for use in conversion.
1167 DocumentClass const * const oldDocClass =
1168 buffer_.params().documentClassPtr();
1169 cur.recordUndoFullDocument();
1170 buffer_.params().setBaseClass(argument);
1171 buffer_.params().makeDocumentClass();
1172 updateLayout(oldDocClass);
1173 processUpdateFlags(Update::Force | Update::FitCursor);
1177 case LFUN_TEXTCLASS_LOAD:
1178 if (buffer_.isInternal())
1180 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1181 LayoutFileList::get().load(argument, buffer_.filePath());
1184 case LFUN_LAYOUT_RELOAD: {
1185 if (buffer_.isInternal())
1187 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1188 LayoutFileIndex bc = buffer_.params().baseClassID();
1189 LayoutFileList::get().reset(bc);
1190 buffer_.params().setBaseClass(bc);
1191 buffer_.params().makeDocumentClass();
1192 updateLayout(oldClass);
1193 processUpdateFlags(Update::Force | Update::FitCursor);
1198 cur.message(_("Undo"));
1199 cur.clearSelection();
1200 if (!cur.textUndo())
1201 cur.message(_("No further undo information"));
1203 processUpdateFlags(Update::Force | Update::FitCursor);
1207 cur.message(_("Redo"));
1208 cur.clearSelection();
1209 if (!cur.textRedo())
1210 cur.message(_("No further redo information"));
1212 processUpdateFlags(Update::Force | Update::FitCursor);
1215 case LFUN_FONT_STATE:
1216 cur.message(cur.currentState());
1219 case LFUN_BOOKMARK_SAVE:
1220 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1223 case LFUN_LABEL_GOTO: {
1224 docstring label = cmd.argument();
1225 if (label.empty()) {
1227 getInsetByCode<InsetRef>(cur, REF_CODE);
1229 label = inset->getParam("reference");
1230 // persistent=false: use temp_bookmark
1239 case LFUN_INSET_EDIT: {
1240 FuncRequest fr(cmd);
1241 // if there is an inset at cursor, see whether it
1243 Inset * inset = cur.nextInset();
1245 inset->dispatch(cur, fr);
1246 // if it did not work, try the underlying inset.
1247 if (!inset || !cur.result().dispatched())
1250 // FIXME I'm adding the last break to solve a crash,
1251 // but that is obviously not right.
1252 if (!cur.result().dispatched())
1253 // It did not work too; no action needed.
1258 case LFUN_PARAGRAPH_GOTO: {
1259 int const id = convert<int>(cmd.getArg(0));
1260 int const pos = convert<int>(cmd.getArg(1));
1262 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1263 b = theBufferList().next(b)) {
1265 DocIterator dit = b->getParFromID(id);
1267 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1271 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1272 << " found in buffer `"
1273 << b->absFileName() << "'.");
1275 if (b == &buffer_) {
1279 processUpdateFlags(Update::Force | Update::FitCursor);
1281 // Switch to other buffer view and resend cmd
1282 theLyXFunc().dispatch(FuncRequest(
1283 LFUN_BUFFER_SWITCH, b->absFileName()));
1284 theLyXFunc().dispatch(cmd);
1291 case LFUN_NOTE_NEXT:
1292 gotoInset(this, NOTE_CODE, false);
1295 case LFUN_REFERENCE_NEXT: {
1296 vector<InsetCode> tmp;
1297 tmp.push_back(LABEL_CODE);
1298 tmp.push_back(REF_CODE);
1299 gotoInset(this, tmp, true);
1303 case LFUN_CHANGES_TRACK:
1304 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1307 case LFUN_CHANGES_OUTPUT:
1308 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1309 if (buffer_.params().outputChanges) {
1310 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1311 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1312 LaTeXFeatures::isAvailable("xcolor");
1314 if (!dvipost && !xcolorulem) {
1315 Alert::warning(_("Changes not shown in LaTeX output"),
1316 _("Changes will not be highlighted in LaTeX output, "
1317 "because neither dvipost nor xcolor/ulem are installed.\n"
1318 "Please install these packages or redefine "
1319 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1320 } else if (!xcolorulem) {
1321 Alert::warning(_("Changes not shown in LaTeX output"),
1322 _("Changes will not be highlighted in LaTeX output "
1323 "when using pdflatex, because xcolor and ulem are not installed.\n"
1324 "Please install both packages or redefine "
1325 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1330 case LFUN_CHANGE_NEXT:
1331 findNextChange(this);
1332 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1333 processUpdateFlags(Update::Force | Update::FitCursor);
1336 case LFUN_CHANGE_PREVIOUS:
1337 findPreviousChange(this);
1338 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1339 processUpdateFlags(Update::Force | Update::FitCursor);
1342 case LFUN_CHANGES_MERGE:
1343 if (findNextChange(this) || findPreviousChange(this)) {
1344 processUpdateFlags(Update::Force | Update::FitCursor);
1345 showDialog("changes");
1349 case LFUN_ALL_CHANGES_ACCEPT:
1350 // select complete document
1351 cur.reset(buffer_.inset());
1352 cur.selHandle(true);
1353 buffer_.text().cursorBottom(cur);
1354 // accept everything in a single step to support atomic undo
1355 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
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_ALL_CHANGES_REJECT:
1361 // select complete document
1362 cur.reset(buffer_.inset());
1363 cur.selHandle(true);
1364 buffer_.text().cursorBottom(cur);
1365 // reject everything in a single step to support atomic undo
1366 // Note: reject does not work recursively; the user may have to repeat the operation
1367 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1368 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1369 processUpdateFlags(Update::Force | Update::FitCursor);
1372 case LFUN_WORD_FIND_FORWARD:
1373 case LFUN_WORD_FIND_BACKWARD: {
1374 static docstring last_search;
1375 docstring searched_string;
1377 if (!cmd.argument().empty()) {
1378 last_search = cmd.argument();
1379 searched_string = cmd.argument();
1381 searched_string = last_search;
1384 if (searched_string.empty())
1387 bool const fw = cmd.action == LFUN_WORD_FIND_FORWARD;
1388 docstring const data =
1389 find2string(searched_string, true, false, fw);
1390 find(this, FuncRequest(LFUN_WORD_FIND, data));
1394 case LFUN_WORD_FIND: {
1395 FuncRequest req = cmd;
1396 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1397 req = d->search_request_cache_;
1398 if (req.argument().empty()) {
1399 theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1402 if (find(this, req))
1405 message(_("String not found!"));
1406 d->search_request_cache_ = req;
1410 case LFUN_WORD_REPLACE: {
1411 bool has_deleted = false;
1412 if (cur.selection()) {
1413 DocIterator beg = cur.selectionBegin();
1414 DocIterator end = cur.selectionEnd();
1415 if (beg.pit() == end.pit()) {
1416 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1417 if (cur.paragraph().isDeleted(p))
1422 replace(this, cmd, has_deleted);
1426 case LFUN_WORD_FINDADV:
1431 cur.clearSelection();
1432 cur.message(from_utf8(N_("Mark off")));
1436 cur.clearSelection();
1438 cur.message(from_utf8(N_("Mark on")));
1441 case LFUN_MARK_TOGGLE:
1442 cur.setSelection(false);
1445 cur.message(from_utf8(N_("Mark removed")));
1448 cur.message(from_utf8(N_("Mark set")));
1453 case LFUN_SCREEN_SHOW_CURSOR:
1457 case LFUN_SCREEN_RECENTER:
1461 case LFUN_BIBTEX_DATABASE_ADD: {
1462 Cursor tmpcur = cur;
1463 findInset(tmpcur, BIBTEX_CODE, false);
1464 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1467 if (inset->addDatabase(cmd.argument()))
1468 buffer_.updateBibfilesCache();
1473 case LFUN_BIBTEX_DATABASE_DEL: {
1474 Cursor tmpcur = cur;
1475 findInset(tmpcur, BIBTEX_CODE, false);
1476 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1479 if (inset->delDatabase(cmd.argument()))
1480 buffer_.updateBibfilesCache();
1485 case LFUN_STATISTICS: {
1486 DocIterator from, to;
1487 if (cur.selection()) {
1488 from = cur.selectionBegin();
1489 to = cur.selectionEnd();
1491 from = doc_iterator_begin(&buffer_);
1492 to = doc_iterator_end(&buffer_);
1494 int const words = countWords(from, to);
1495 int const chars = countChars(from, to, false);
1496 int const chars_blanks = countChars(from, to, true);
1498 if (cur.selection())
1499 message = _("Statistics for the selection:");
1501 message = _("Statistics for the document:");
1504 message += bformat(_("%1$d words"), words);
1506 message += _("One word");
1508 if (chars_blanks != 1)
1509 message += bformat(_("%1$d characters (including blanks)"),
1512 message += _("One character (including blanks)");
1515 message += bformat(_("%1$d characters (excluding blanks)"),
1518 message += _("One character (excluding blanks)");
1520 Alert::information(_("Statistics"), message);
1524 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1525 // turn compression on/off
1526 buffer_.params().compressed = !buffer_.params().compressed;
1529 case LFUN_LABEL_COPY_AS_REF: {
1530 // if there is an inset at cursor, try to copy it
1531 Inset * inset = &cur.inset();
1532 if (!inset || !inset->asInsetMath())
1533 inset = cur.nextInset();
1535 FuncRequest tmpcmd = cmd;
1536 inset->dispatch(cur, tmpcmd);
1538 if (!cur.result().dispatched())
1539 // It did not work too; no action needed.
1541 cur.clearSelection();
1542 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1546 case LFUN_NEXT_INSET_MODIFY: {
1547 // create the the real function we want to invoke
1548 FuncRequest tmpcmd = cmd;
1549 tmpcmd.action = LFUN_INSET_MODIFY;
1550 // if there is an inset at cursor, see whether it
1552 Inset * inset = cur.nextInset();
1555 inset->dispatch(cur, tmpcmd);
1557 // if it did not work, try the underlying inset.
1558 if (!inset || !cur.result().dispatched()) {
1560 cur.dispatch(tmpcmd);
1563 if (!cur.result().dispatched())
1564 // It did not work too; no action needed.
1566 cur.clearSelection();
1567 processUpdateFlags(Update::Force | Update::FitCursor);
1571 case LFUN_SCREEN_UP:
1572 case LFUN_SCREEN_DOWN: {
1573 Point p = getPos(cur, cur.boundary());
1574 // This code has been commented out to enable to scroll down a
1575 // document, even if there are large insets in it (see bug #5465).
1576 /*if (p.y_ < 0 || p.y_ > height_) {
1577 // The cursor is off-screen so recenter before proceeding.
1579 p = getPos(cur, cur.boundary());
1581 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1582 ? -height_ : height_);
1583 if (cmd.action == LFUN_SCREEN_UP && scrolled > -height_)
1585 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1586 p = Point(width_, height_);
1588 bool const in_texted = cur.inTexted();
1589 cur.reset(buffer_.inset());
1592 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1593 true, cmd.action == LFUN_SCREEN_UP);
1594 //FIXME: what to do with cur.x_target()?
1595 bool update = in_texted && cur.bv().checkDepm(cur, old);
1598 processUpdateFlags(Update::Force | Update::FitCursor);
1606 case LFUN_SCREEN_UP_SELECT: {
1607 cur.selHandle(true);
1608 if (isTopScreen()) {
1609 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1613 int y = getPos(cur, cur.boundary()).y_;
1614 int const ymin = y - height_ + defaultRowHeight();
1615 while (y > ymin && cur.up())
1616 y = getPos(cur, cur.boundary()).y_;
1619 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1623 case LFUN_SCREEN_DOWN_SELECT: {
1624 cur.selHandle(true);
1625 if (isBottomScreen()) {
1626 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1630 int y = getPos(cur, cur.boundary()).y_;
1631 int const ymax = y + height_ - defaultRowHeight();
1632 while (y < ymax && cur.down())
1633 y = getPos(cur, cur.boundary()).y_;
1636 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1640 // This could be rewriten using some command like forall <insetname> <command>
1641 // once the insets refactoring is done.
1642 case LFUN_NOTES_MUTATE: {
1643 if (cmd.argument().empty())
1646 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1647 processUpdateFlags(Update::Force);
1652 case LFUN_ALL_INSETS_TOGGLE: {
1654 string const name = split(to_utf8(cmd.argument()), action, ' ');
1655 InsetCode const inset_code = insetCode(name);
1657 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1659 Inset & inset = cur.buffer()->inset();
1660 InsetIterator it = inset_iterator_begin(inset);
1661 InsetIterator const end = inset_iterator_end(inset);
1662 for (; it != end; ++it) {
1663 if (it->asInsetCollapsable()
1664 && (inset_code == NO_CODE
1665 || inset_code == it->lyxCode())) {
1666 Cursor tmpcur = cur;
1667 tmpcur.pushBackward(*it);
1668 it->dispatch(tmpcur, fr);
1671 processUpdateFlags(Update::Force | Update::FitCursor);
1675 case LFUN_BRANCH_ADD_INSERT: {
1676 docstring branch_name = from_utf8(cmd.getArg(0));
1677 if (branch_name.empty())
1678 if (!Alert::askForText(branch_name, _("Branch name")) ||
1679 branch_name.empty())
1682 DispatchResult drtmp;
1683 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1684 if (drtmp.error()) {
1685 Alert::warning(_("Branch already exists"), drtmp.message());
1688 BranchList & branch_list = buffer_.params().branchlist();
1689 Branch const * branch = branch_list.find(branch_name);
1690 string const x11hexname = X11hexname(branch->color());
1691 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1692 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1693 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1697 case LFUN_KEYMAP_OFF:
1698 getIntl().keyMapOn(false);
1701 case LFUN_KEYMAP_PRIMARY:
1702 getIntl().keyMapPrim();
1705 case LFUN_KEYMAP_SECONDARY:
1706 getIntl().keyMapSec();
1709 case LFUN_KEYMAP_TOGGLE:
1710 getIntl().toggleKeyMap();
1721 docstring const BufferView::requestSelection()
1723 Cursor & cur = d->cursor_;
1725 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1726 if (!cur.selection()) {
1727 d->xsel_cache_.set = false;
1731 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1732 if (!d->xsel_cache_.set ||
1733 cur.top() != d->xsel_cache_.cursor ||
1734 cur.anchor_.top() != d->xsel_cache_.anchor)
1736 d->xsel_cache_.cursor = cur.top();
1737 d->xsel_cache_.anchor = cur.anchor_.top();
1738 d->xsel_cache_.set = cur.selection();
1739 return cur.selectionAsString(false);
1745 void BufferView::clearSelection()
1747 d->cursor_.clearSelection();
1748 // Clear the selection buffer. Otherwise a subsequent
1749 // middle-mouse-button paste would use the selection buffer,
1750 // not the more current external selection.
1751 cap::clearSelection();
1752 d->xsel_cache_.set = false;
1753 // The buffer did not really change, but this causes the
1754 // redraw we need because we cleared the selection above.
1759 void BufferView::resize(int width, int height)
1761 // Update from work area
1765 // Clear the paragraph height cache.
1766 d->par_height_.clear();
1767 // Redo the metrics.
1772 Inset const * BufferView::getCoveringInset(Text const & text,
1775 TextMetrics & tm = d->text_metrics_[&text];
1776 Inset * inset = tm.checkInsetHit(x, y);
1780 if (!inset->descendable())
1781 // No need to go further down if the inset is not
1785 size_t cell_number = inset->nargs();
1786 // Check all the inner cell.
1787 for (size_t i = 0; i != cell_number; ++i) {
1788 Text const * inner_text = inset->getText(i);
1791 Inset const * inset_deeper =
1792 getCoveringInset(*inner_text, x, y);
1794 return inset_deeper;
1802 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1804 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1806 // This is only called for mouse related events including
1807 // LFUN_FILE_OPEN generated by drag-and-drop.
1808 FuncRequest cmd = cmd0;
1810 Cursor old = cursor();
1812 cur.push(buffer_.inset());
1813 cur.setSelection(d->cursor_.selection());
1815 // Either the inset under the cursor or the
1816 // surrounding Text will handle this event.
1818 // make sure we stay within the screen...
1819 cmd.y = min(max(cmd.y, -1), height_);
1821 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1823 // Get inset under mouse, if there is one.
1824 Inset const * covering_inset =
1825 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1826 if (covering_inset == d->last_inset_)
1827 // Same inset, no need to do anything...
1830 bool need_redraw = false;
1831 // const_cast because of setMouseHover().
1832 Inset * inset = const_cast<Inset *>(covering_inset);
1834 // Remove the hint on the last hovered inset (if any).
1835 need_redraw |= d->last_inset_->setMouseHover(false);
1837 // Highlighted the newly hovered inset (if any).
1838 need_redraw |= inset->setMouseHover(true);
1839 d->last_inset_ = inset;
1843 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1844 << cmd.x << ", " << cmd.y << ")");
1846 d->update_strategy_ = DecorationUpdate;
1848 // This event (moving without mouse click) is not passed further.
1849 // This should be changed if it is further utilized.
1854 // Build temporary cursor.
1855 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1857 // Put anchor at the same position.
1860 cur.beginUndoGroup();
1862 // Try to dispatch to an non-editable inset near this position
1863 // via the temp cursor. If the inset wishes to change the real
1864 // cursor it has to do so explicitly by using
1865 // cur.bv().cursor() = cur; (or similar)
1867 inset->dispatch(cur, cmd);
1869 // Now dispatch to the temporary cursor. If the real cursor should
1870 // be modified, the inset's dispatch has to do so explicitly.
1871 if (!inset || !cur.result().dispatched())
1876 // Notify left insets
1879 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
1881 cursor().fixIfBroken();
1884 // Do we have a selection?
1885 theSelection().haveSelection(cursor().selection());
1887 // If the command has been dispatched,
1888 if (cur.result().dispatched() || cur.result().update())
1889 processUpdateFlags(cur.result().update());
1893 void BufferView::lfunScroll(FuncRequest const & cmd)
1895 string const scroll_type = cmd.getArg(0);
1896 int const scroll_step =
1897 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1898 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1899 if (scroll_step == 0)
1901 string const scroll_quantity = cmd.getArg(1);
1902 if (scroll_quantity == "up")
1903 scrollUp(scroll_step);
1904 else if (scroll_quantity == "down")
1905 scrollDown(scroll_step);
1907 int const scroll_value = convert<int>(scroll_quantity);
1909 scroll(scroll_step * scroll_value);
1916 int BufferView::minVisiblePart()
1918 return 2 * defaultRowHeight();
1922 int BufferView::scroll(int y)
1925 return scrollDown(y);
1927 return scrollUp(-y);
1932 int BufferView::scrollDown(int offset)
1934 Text * text = &buffer_.text();
1935 TextMetrics & tm = d->text_metrics_[text];
1936 int const ymax = height_ + offset;
1938 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1939 int bottom_pos = last.second->position() + last.second->descent();
1940 if (lyxrc.scroll_below_document)
1941 bottom_pos += height_ - minVisiblePart();
1942 if (last.first + 1 == int(text->paragraphs().size())) {
1943 if (bottom_pos <= height_)
1945 offset = min(offset, bottom_pos - height_);
1948 if (bottom_pos > ymax)
1950 tm.newParMetricsDown();
1952 d->anchor_ypos_ -= offset;
1957 int BufferView::scrollUp(int offset)
1959 Text * text = &buffer_.text();
1960 TextMetrics & tm = d->text_metrics_[text];
1961 int ymin = - offset;
1963 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1964 int top_pos = first.second->position() - first.second->ascent();
1965 if (first.first == 0) {
1968 offset = min(offset, - top_pos);
1973 tm.newParMetricsUp();
1975 d->anchor_ypos_ += offset;
1980 void BufferView::setCursorFromRow(int row)
1985 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1987 d->cursor_.reset(buffer_.inset());
1989 buffer_.text().setCursor(d->cursor_, 0, 0);
1991 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1995 bool BufferView::setCursorFromInset(Inset const * inset)
1997 // are we already there?
1998 if (cursor().nextInset() == inset)
2001 // Inset is not at cursor position. Find it in the document.
2003 cur.reset(buffer().inset());
2004 while (cur && cur.nextInset() != inset)
2015 void BufferView::gotoLabel(docstring const & label)
2017 std::vector<Buffer const *> bufs = buffer().allRelatives();
2018 std::vector<Buffer const *>::iterator it = bufs.begin();
2019 for (; it != bufs.end(); ++it) {
2020 Buffer const * buf = *it;
2023 Toc & toc = buf->tocBackend().toc("label");
2024 TocIterator toc_it = toc.begin();
2025 TocIterator end = toc.end();
2026 for (; toc_it != end; ++toc_it) {
2027 if (label == toc_it->str()) {
2028 dispatch(toc_it->action());
2036 TextMetrics const & BufferView::textMetrics(Text const * t) const
2038 return const_cast<BufferView *>(this)->textMetrics(t);
2042 TextMetrics & BufferView::textMetrics(Text const * t)
2044 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2045 if (tmc_it == d->text_metrics_.end()) {
2046 tmc_it = d->text_metrics_.insert(
2047 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2049 return tmc_it->second;
2053 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2056 return textMetrics(t).parMetrics(pit);
2060 int BufferView::workHeight() const
2066 void BufferView::setCursor(DocIterator const & dit)
2068 d->cursor_.reset(buffer().inset());
2069 size_t const n = dit.depth();
2070 for (size_t i = 0; i < n; ++i)
2071 dit[i].inset().edit(d->cursor_, true);
2073 d->cursor_.setCursor(dit);
2074 d->cursor_.setSelection(false);
2078 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2080 // Would be wrong to delete anything if we have a selection.
2081 if (cur.selection())
2084 bool need_anchor_change = false;
2085 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2086 need_anchor_change);
2088 if (need_anchor_change)
2096 buffer_.updateLabels();
2104 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2106 LASSERT(&cur.bv() == this, /**/);
2109 // this event will clear selection so we save selection for
2110 // persistent selection
2111 cap::saveSelection(cursor());
2113 // Has the cursor just left the inset?
2114 bool leftinset = (&d->cursor_.inset() != &cur.inset());
2116 d->cursor_.fixIfBroken();
2118 // FIXME: shift-mouse selection doesn't work well across insets.
2119 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
2121 // do the dEPM magic if needed
2122 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2123 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2124 // the leftinset bool would not be necessary (badcursor instead).
2125 bool update = leftinset;
2126 if (!do_selection && d->cursor_.inTexted())
2127 update |= checkDepm(cur, d->cursor_);
2128 d->cursor_.macroModeClose();
2130 d->cursor_.resetAnchor();
2131 d->cursor_.setCursor(cur);
2132 d->cursor_.boundary(cur.boundary());
2134 d->cursor_.setSelection();
2136 d->cursor_.clearSelection();
2138 d->cursor_.finishUndo();
2139 d->cursor_.setCurrentFont();
2144 void BufferView::putSelectionAt(DocIterator const & cur,
2145 int length, bool backwards)
2147 d->cursor_.clearSelection();
2153 d->cursor_.pos() += length;
2154 d->cursor_.setSelection(d->cursor_, -length);
2156 d->cursor_.setSelection(d->cursor_, length);
2158 // Ensure a redraw happens in any case because the new selection could
2159 // possibly be on the same screen as the previous selection.
2160 processUpdateFlags(Update::Force | Update::FitCursor);
2164 Cursor & BufferView::cursor()
2170 Cursor const & BufferView::cursor() const
2176 pit_type BufferView::anchor_ref() const
2178 return d->anchor_pit_;
2182 bool BufferView::singleParUpdate()
2184 Text & buftext = buffer_.text();
2185 pit_type const bottom_pit = d->cursor_.bottom().pit();
2186 TextMetrics & tm = textMetrics(&buftext);
2187 int old_height = tm.parMetrics(bottom_pit).height();
2189 // make sure inline completion pointer is ok
2190 if (d->inlineCompletionPos_.fixIfBroken())
2191 d->inlineCompletionPos_ = DocIterator();
2193 // In Single Paragraph mode, rebreak only
2194 // the (main text, not inset!) paragraph containing the cursor.
2195 // (if this paragraph contains insets etc., rebreaking will
2196 // recursively descend)
2197 tm.redoParagraph(bottom_pit);
2198 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2199 if (pm.height() != old_height)
2200 // Paragraph height has changed so we cannot proceed to
2201 // the singlePar optimisation.
2204 d->update_strategy_ = SingleParUpdate;
2206 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2207 << " y2: " << pm.position() + pm.descent()
2208 << " pit: " << bottom_pit
2209 << " singlepar: 1");
2214 void BufferView::updateMetrics()
2216 if (height_ == 0 || width_ == 0)
2219 Text & buftext = buffer_.text();
2220 pit_type const npit = int(buftext.paragraphs().size());
2222 // Clear out the position cache in case of full screen redraw,
2223 d->coord_cache_.clear();
2225 // Clear out paragraph metrics to avoid having invalid metrics
2226 // in the cache from paragraphs not relayouted below
2227 // The complete text metrics will be redone.
2228 d->text_metrics_.clear();
2230 TextMetrics & tm = textMetrics(&buftext);
2232 // make sure inline completion pointer is ok
2233 if (d->inlineCompletionPos_.fixIfBroken())
2234 d->inlineCompletionPos_ = DocIterator();
2236 if (d->anchor_pit_ >= npit)
2237 // The anchor pit must have been deleted...
2238 d->anchor_pit_ = npit - 1;
2240 // Rebreak anchor paragraph.
2241 tm.redoParagraph(d->anchor_pit_);
2242 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2245 if (d->anchor_pit_ == 0) {
2246 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2248 // Complete buffer visible? Then it's easy.
2249 if (scrollRange == 0)
2250 d->anchor_ypos_ = anchor_pm.ascent();
2252 // FIXME: Some clever handling needed to show
2253 // the _first_ paragraph up to the top if the cursor is
2254 // in the first line.
2256 anchor_pm.setPosition(d->anchor_ypos_);
2258 LYXERR(Debug::PAINTING, "metrics: "
2259 << " anchor pit = " << d->anchor_pit_
2260 << " anchor ypos = " << d->anchor_ypos_);
2262 // Redo paragraphs above anchor if necessary.
2263 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2264 // We are now just above the anchor paragraph.
2265 pit_type pit1 = d->anchor_pit_ - 1;
2266 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2267 tm.redoParagraph(pit1);
2268 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2270 // Save the paragraph position in the cache.
2275 // Redo paragraphs below the anchor if necessary.
2276 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2277 // We are now just below the anchor paragraph.
2278 pit_type pit2 = d->anchor_pit_ + 1;
2279 for (; pit2 < npit && y2 <= height_; ++pit2) {
2280 tm.redoParagraph(pit2);
2281 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2283 // Save the paragraph position in the cache.
2288 LYXERR(Debug::PAINTING, "Metrics: "
2289 << " anchor pit = " << d->anchor_pit_
2290 << " anchor ypos = " << d->anchor_ypos_
2293 << " pit1 = " << pit1
2294 << " pit2 = " << pit2);
2296 d->update_strategy_ = FullScreenUpdate;
2298 if (lyxerr.debugging(Debug::WORKAREA)) {
2299 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2300 d->coord_cache_.dump();
2305 void BufferView::insertLyXFile(FileName const & fname)
2307 LASSERT(d->cursor_.inTexted(), /**/);
2309 // Get absolute path of file and add ".lyx"
2310 // to the filename if necessary
2311 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2313 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2314 // emit message signal.
2315 message(bformat(_("Inserting document %1$s..."), disp_fn));
2318 Buffer buf("", false);
2319 if (buf.loadLyXFile(filename)) {
2320 ErrorList & el = buffer_.errorList("Parse");
2321 // Copy the inserted document error list into the current buffer one.
2322 el = buf.errorList("Parse");
2323 buffer_.undo().recordUndo(d->cursor_);
2324 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2325 buf.params().documentClassPtr(), el);
2326 res = _("Document %1$s inserted.");
2328 res = _("Could not insert document %1$s");
2333 // emit message signal.
2334 message(bformat(res, disp_fn));
2335 buffer_.errors("Parse");
2339 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2345 // Addup contribution of nested insets, from inside to outside,
2346 // keeping the outer paragraph for a special handling below
2347 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2348 CursorSlice const & sl = dit[i];
2352 // get relative position inside sl.inset()
2353 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2355 // Make relative position inside of the edited inset relative to sl.inset()
2359 // In case of an RTL inset, the edited inset will be positioned to the left
2362 bool boundary_i = boundary && i + 1 == dit.depth();
2363 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2368 // remember width for the case that sl.inset() is positioned in an RTL inset
2369 if (i && dit[i - 1].text()) {
2370 // If this Inset is inside a Text Inset, retrieve the Dimension
2371 // from the containing text instead of using Inset::dimension() which
2372 // might not be implemented.
2373 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2374 // elimination of Inset::dim_ cache. This coordOffset() method needs
2375 // to be rewritten in light of the new design.
2376 Dimension const & dim = parMetrics(dit[i - 1].text(),
2377 dit[i - 1].pit()).insetDimension(&sl.inset());
2380 Dimension const dim = sl.inset().dimension(*this);
2384 //lyxerr << "Cursor::getPos, i: "
2385 // << i << " x: " << xx << " y: " << y << endl;
2388 // Add contribution of initial rows of outermost paragraph
2389 CursorSlice const & sl = dit[0];
2390 TextMetrics const & tm = textMetrics(sl.text());
2391 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2392 LASSERT(!pm.rows().empty(), /**/);
2393 y -= pm.rows()[0].ascent();
2395 // FIXME: document this mess
2397 if (sl.pos() > 0 && dit.depth() == 1) {
2399 if (pos && boundary)
2401 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2402 rend = pm.pos2row(pos);
2404 rend = pm.pos2row(sl.pos());
2406 size_t rend = pm.pos2row(sl.pos());
2408 for (size_t rit = 0; rit != rend; ++rit)
2409 y += pm.rows()[rit].height();
2410 y += pm.rows()[rend].ascent();
2412 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2414 // Make relative position from the nested inset now bufferview absolute.
2415 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2418 // In the RTL case place the nested inset at the left of the cursor in
2419 // the outer paragraph
2420 bool boundary_1 = boundary && 1 == dit.depth();
2421 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2429 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2431 if (!paragraphVisible(dit))
2432 return Point(-1, -1);
2434 CursorSlice const & bot = dit.bottom();
2435 TextMetrics const & tm = textMetrics(bot.text());
2437 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2438 p.y_ += tm.parMetrics(bot.pit()).position();
2443 bool BufferView::paragraphVisible(DocIterator const & dit) const
2445 CursorSlice const & bot = dit.bottom();
2446 TextMetrics const & tm = textMetrics(bot.text());
2448 return tm.contains(bot.pit());
2452 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2454 Cursor const & cur = cursor();
2455 Font const font = cur.getFont();
2456 frontend::FontMetrics const & fm = theFontMetrics(font);
2457 int const asc = fm.maxAscent();
2458 int const des = fm.maxDescent();
2460 p = getPos(cur, cur.boundary());
2465 bool BufferView::cursorInView(Point const & p, int h) const
2467 Cursor const & cur = cursor();
2468 // does the cursor touch the screen ?
2469 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2475 void BufferView::draw(frontend::Painter & pain)
2477 if (height_ == 0 || width_ == 0)
2479 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2481 Text & text = buffer_.text();
2482 TextMetrics const & tm = d->text_metrics_[&text];
2483 int const y = tm.first().second->position();
2484 PainterInfo pi(this, pain);
2486 switch (d->update_strategy_) {
2488 case NoScreenUpdate:
2489 // If no screen painting is actually needed, only some the different
2490 // coordinates of insets and paragraphs needs to be updated.
2491 pi.full_repaint = true;
2492 pi.pain.setDrawingEnabled(false);
2496 case SingleParUpdate:
2497 pi.full_repaint = false;
2498 // In general, only the current row of the outermost paragraph
2499 // will be redrawn. Particular cases where selection spans
2500 // multiple paragraph are correctly detected in TextMetrics.
2504 case DecorationUpdate:
2505 // FIXME: We should also distinguish DecorationUpdate to avoid text
2506 // drawing if possible. This is not possible to do easily right now
2507 // because of the single backing pixmap.
2509 case FullScreenUpdate:
2510 // The whole screen, including insets, will be refreshed.
2511 pi.full_repaint = true;
2513 // Clear background.
2514 pain.fillRectangle(0, 0, width_, height_,
2515 pi.backgroundColor(&buffer_.inset()));
2520 // and possibly grey out below
2521 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2522 int const y2 = lastpm.second->position() + lastpm.second->descent();
2525 Color color = buffer().isInternal()
2526 ? Color_background : Color_bottomarea;
2527 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2531 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2533 // The scrollbar needs an update.
2536 // Normalize anchor for next time
2537 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2538 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2539 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2540 ParagraphMetrics const & pm = tm.parMetrics(pit);
2541 if (pm.position() + pm.descent() > 0) {
2542 d->anchor_pit_ = pit;
2543 d->anchor_ypos_ = pm.position();
2547 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2548 << " anchor ypos = " << d->anchor_ypos_);
2552 void BufferView::message(docstring const & msg)
2555 d->gui_->message(msg);
2559 void BufferView::showDialog(string const & name)
2562 d->gui_->showDialog(name, string());
2566 void BufferView::showDialog(string const & name,
2567 string const & data, Inset * inset)
2570 d->gui_->showDialog(name, data, inset);
2574 void BufferView::updateDialog(string const & name, string const & data)
2577 d->gui_->updateDialog(name, data);
2581 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2587 // FIXME: Move this out of BufferView again
2588 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2590 if (!fname.isReadableFile()) {
2591 docstring const error = from_ascii(strerror(errno));
2592 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2593 docstring const text =
2594 bformat(_("Could not read the specified document\n"
2595 "%1$s\ndue to the error: %2$s"), file, error);
2596 Alert::error(_("Could not read file"), text);
2600 if (!fname.isReadableFile()) {
2601 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2602 docstring const text =
2603 bformat(_("%1$s\n is not readable."), file);
2604 Alert::error(_("Could not open file"), text);
2608 // FIXME UNICODE: We don't know the encoding of the file
2609 docstring file_content = fname.fileContents("UTF-8");
2610 if (file_content.empty()) {
2611 Alert::error(_("Reading not UTF-8 encoded file"),
2612 _("The file is not UTF-8 encoded.\n"
2613 "It will be read as local 8Bit-encoded.\n"
2614 "If this does not give the correct result\n"
2615 "then please change the encoding of the file\n"
2616 "to UTF-8 with a program other than LyX.\n"));
2617 file_content = fname.fileContents("local8bit");
2620 return normalize_c(file_content);
2624 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2626 docstring const tmpstr = contentsOfPlaintextFile(f);
2631 Cursor & cur = cursor();
2632 cap::replaceSelection(cur);
2633 buffer_.undo().recordUndo(cur);
2635 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2637 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2644 docstring const & BufferView::inlineCompletion() const
2646 return d->inlineCompletion_;
2650 size_t const & BufferView::inlineCompletionUniqueChars() const
2652 return d->inlineCompletionUniqueChars_;
2656 DocIterator const & BufferView::inlineCompletionPos() const
2658 return d->inlineCompletionPos_;
2662 bool samePar(DocIterator const & a, DocIterator const & b)
2664 if (a.empty() && b.empty())
2666 if (a.empty() || b.empty())
2668 if (a.depth() != b.depth())
2670 return &a.innerParagraph() == &b.innerParagraph();
2674 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2675 docstring const & completion, size_t uniqueChars)
2677 uniqueChars = min(completion.size(), uniqueChars);
2678 bool changed = d->inlineCompletion_ != completion
2679 || d->inlineCompletionUniqueChars_ != uniqueChars;
2680 bool singlePar = true;
2681 d->inlineCompletion_ = completion;
2682 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2684 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2687 DocIterator const & old = d->inlineCompletionPos_;
2689 //lyxerr << "inlineCompletionPos changed" << std::endl;
2690 // old or pos are in another paragraph?
2691 if ((!samePar(cur, pos) && !pos.empty())
2692 || (!samePar(cur, old) && !old.empty())) {
2694 //lyxerr << "different paragraph" << std::endl;
2696 d->inlineCompletionPos_ = pos;
2701 if (singlePar && !(cur.disp_.update() & Update::Force))
2702 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2704 cur.updateFlags(cur.disp_.update() | Update::Force);