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"
40 #include "LyXAction.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/InsetNote.h"
62 #include "insets/InsetRef.h"
63 #include "insets/InsetText.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), clickable_inset_(false),
224 mouse_position_cache_(),
225 bookmark_edit_position_(-1), gui_(0)
229 ScrollbarParameters scrollbarParameters_;
231 ScreenUpdateStrategy update_strategy_;
233 CoordCache coord_cache_;
235 /// Estimated average par height for scrollbar.
237 /// this is used to handle XSelection events in the right manner.
246 pit_type anchor_pit_;
250 vector<int> par_height_;
253 DocIterator inlineCompletionPos_;
255 docstring inlineCompletion_;
257 size_t inlineCompletionUniqueChars_;
259 /// keyboard mapping object.
262 /// last visited inset.
263 /** kept to send setMouseHover(false).
264 * Not owned, so don't delete.
267 /// are we hovering something that we can click
268 bool clickable_inset_;
270 /// position of the mouse at the time of the last mouse move
271 /// This is used to update the hovering status of inset in
272 /// cases where the buffer is scrolled, but the mouse didn't move.
273 Point mouse_position_cache_;
275 // cache for id of the paragraph which was edited the last time
276 int bookmark_edit_position_;
278 mutable TextMetricsCache text_metrics_;
281 /** Not owned, so don't delete.
283 frontend::GuiBufferViewDelegate * gui_;
285 /// Cache for Find Next
286 FuncRequest search_request_cache_;
289 map<string, Inset *> edited_insets_;
293 BufferView::BufferView(Buffer & buf)
294 : width_(0), height_(0), full_screen_(false), buffer_(buf),
295 d(new Private(*this))
297 d->xsel_cache_.set = false;
298 d->intl_.initKeyMapper(lyxrc.use_kbmap);
300 d->cursor_.setBuffer(&buf);
301 d->cursor_.push(buffer_.inset());
302 d->cursor_.resetAnchor();
303 d->cursor_.setCurrentFont();
305 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
306 thePreviews().generateBufferPreviews(buffer_);
310 BufferView::~BufferView()
312 // current buffer is going to be switched-off, save cursor pos
313 // Ideally, the whole cursor stack should be saved, but session
314 // currently can only handle bottom (whole document) level pit and pos.
315 // That is to say, if a cursor is in a nested inset, it will be
316 // restore to the left of the top level inset.
317 LastFilePosSection::FilePos fp;
318 fp.pit = d->cursor_.bottom().pit();
319 fp.pos = d->cursor_.bottom().pos();
320 theSession().lastFilePos().save(buffer_.fileName(), fp);
323 d->last_inset_->setMouseHover(this, false);
329 int BufferView::rightMargin() const
331 // The additional test for the case the outliner is opened.
333 !lyxrc.full_screen_limit ||
334 width_ < lyxrc.full_screen_width + 20)
337 return (width_ - lyxrc.full_screen_width) / 2;
341 int BufferView::leftMargin() const
343 return rightMargin();
347 bool BufferView::isTopScreen() const
349 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
353 bool BufferView::isBottomScreen() const
355 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
359 Intl & BufferView::getIntl()
365 Intl const & BufferView::getIntl() const
371 CoordCache & BufferView::coordCache()
373 return d->coord_cache_;
377 CoordCache const & BufferView::coordCache() const
379 return d->coord_cache_;
383 Buffer & BufferView::buffer()
389 Buffer const & BufferView::buffer() const
395 bool BufferView::fitCursor()
397 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
398 frontend::FontMetrics const & fm =
399 theFontMetrics(d->cursor_.getFont().fontInfo());
400 int const asc = fm.maxAscent();
401 int const des = fm.maxDescent();
402 Point const p = getPos(d->cursor_);
403 if (p.y_ - asc >= 0 && p.y_ + des < height_)
410 void BufferView::processUpdateFlags(Update::flags flags)
412 // This is close to a hot-path.
413 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
414 << "[fitcursor = " << (flags & Update::FitCursor)
415 << ", forceupdate = " << (flags & Update::Force)
416 << ", singlepar = " << (flags & Update::SinglePar)
417 << "] buffer: " << &buffer_);
419 // FIXME Does this really need doing here? It's done in updateBuffer, and
420 // if the Buffer doesn't need updating, then do the macros?
421 buffer_.updateMacros();
423 // Now do the first drawing step if needed. This consists on updating
424 // the CoordCache in updateMetrics().
425 // The second drawing step is done in WorkArea::redraw() if needed.
427 // Case when no explicit update is requested.
429 // no need to redraw anything.
430 d->update_strategy_ = NoScreenUpdate;
434 if (flags == Update::Decoration) {
435 d->update_strategy_ = DecorationUpdate;
436 buffer_.changed(false);
440 if (flags == Update::FitCursor
441 || flags == (Update::Decoration | Update::FitCursor)) {
442 // tell the frontend to update the screen if needed.
447 if (flags & Update::Decoration) {
448 d->update_strategy_ = DecorationUpdate;
449 buffer_.changed(false);
452 // no screen update is needed.
453 d->update_strategy_ = NoScreenUpdate;
457 bool const full_metrics = flags & Update::Force || !singleParUpdate();
460 // We have to update the full screen metrics.
463 if (!(flags & Update::FitCursor)) {
464 // Nothing to do anymore. Trigger a redraw and return
465 buffer_.changed(false);
469 // updateMetrics() does not update paragraph position
470 // This is done at draw() time. So we need a redraw!
471 buffer_.changed(false);
474 // The cursor is off screen so ensure it is visible.
479 updateHoveredInset();
483 void BufferView::updateScrollbar()
485 if (height_ == 0 && width_ == 0)
488 // We prefer fixed size line scrolling.
489 d->scrollbarParameters_.single_step = defaultRowHeight();
490 // We prefer full screen page scrolling.
491 d->scrollbarParameters_.page_step = height_;
493 Text & t = buffer_.text();
494 TextMetrics & tm = d->text_metrics_[&t];
496 LYXERR(Debug::GUI, " Updating scrollbar: height: "
497 << t.paragraphs().size()
498 << " curr par: " << d->cursor_.bottom().pit()
499 << " default height " << defaultRowHeight());
501 size_t const parsize = t.paragraphs().size();
502 if (d->par_height_.size() != parsize) {
503 d->par_height_.clear();
504 // FIXME: We assume a default paragraph height of 2 rows. This
505 // should probably be pondered with the screen width.
506 d->par_height_.resize(parsize, defaultRowHeight() * 2);
509 // Look at paragraph heights on-screen
510 pair<pit_type, ParagraphMetrics const *> first = tm.first();
511 pair<pit_type, ParagraphMetrics const *> last = tm.last();
512 for (pit_type pit = first.first; pit <= last.first; ++pit) {
513 d->par_height_[pit] = tm.parMetrics(pit).height();
514 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
515 << d->par_height_[pit]);
518 int top_pos = first.second->position() - first.second->ascent();
519 int bottom_pos = last.second->position() + last.second->descent();
520 bool first_visible = first.first == 0 && top_pos >= 0;
521 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
522 if (first_visible && last_visible) {
523 d->scrollbarParameters_.min = 0;
524 d->scrollbarParameters_.max = 0;
528 d->scrollbarParameters_.min = top_pos;
529 for (size_t i = 0; i != size_t(first.first); ++i)
530 d->scrollbarParameters_.min -= d->par_height_[i];
531 d->scrollbarParameters_.max = bottom_pos;
532 for (size_t i = last.first + 1; i != parsize; ++i)
533 d->scrollbarParameters_.max += d->par_height_[i];
535 d->scrollbarParameters_.position = 0;
536 // The reference is the top position so we remove one page.
537 if (lyxrc.scroll_below_document)
538 d->scrollbarParameters_.max -= minVisiblePart();
540 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
544 ScrollbarParameters const & BufferView::scrollbarParameters() const
546 return d->scrollbarParameters_;
550 docstring BufferView::toolTip(int x, int y) const
552 // Get inset under mouse, if there is one.
553 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
555 // No inset, no tooltip...
557 return covering_inset->toolTip(*this, x, y);
561 docstring BufferView::contextMenu(int x, int y) const
563 //If there is a selection, return the containing inset menu
564 if (d->cursor_.selection())
565 return d->cursor_.inset().contextMenu(*this, x, y);
567 // Get inset under mouse, if there is one.
568 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
570 return covering_inset->contextMenu(*this, x, y);
572 return buffer_.inset().contextMenu(*this, x, y);
576 void BufferView::scrollDocView(int value, bool update)
578 int const offset = value - d->scrollbarParameters_.position;
580 // No scrolling at all? No need to redraw anything
584 // If the offset is less than 2 screen height, prefer to scroll instead.
585 if (abs(offset) <= 2 * height_) {
586 d->anchor_ypos_ -= offset;
587 buffer_.changed(true);
588 updateHoveredInset();
592 // cut off at the top
593 if (value <= d->scrollbarParameters_.min) {
594 DocIterator dit = doc_iterator_begin(&buffer_);
595 showCursor(dit, false, update);
596 LYXERR(Debug::SCROLLING, "scroll to top");
600 // cut off at the bottom
601 if (value >= d->scrollbarParameters_.max) {
602 DocIterator dit = doc_iterator_end(&buffer_);
604 showCursor(dit, false, update);
605 LYXERR(Debug::SCROLLING, "scroll to bottom");
609 // find paragraph at target position
610 int par_pos = d->scrollbarParameters_.min;
612 for (; i != int(d->par_height_.size()); ++i) {
613 par_pos += d->par_height_[i];
614 if (par_pos >= value)
618 if (par_pos < value) {
619 // It seems we didn't find the correct pit so stay on the safe side and
621 LYXERR0("scrolling position not found!");
622 scrollDocView(d->scrollbarParameters_.max, update);
626 DocIterator dit = doc_iterator_begin(&buffer_);
628 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
629 showCursor(dit, false, update);
633 // FIXME: this method is not working well.
634 void BufferView::setCursorFromScrollbar()
636 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
638 int const height = 2 * defaultRowHeight();
639 int const first = height;
640 int const last = height_ - height;
642 Cursor const & oldcur = d->cursor_;
644 switch (cursorStatus(oldcur)) {
652 int const y = getPos(oldcur).y_;
653 newy = min(last, max(y, first));
657 // We reset the cursor because cursorStatus() does not
658 // work when the cursor is within mathed.
661 tm.setCursorFromCoordinates(cur, 0, newy);
663 // update the bufferview cursor and notify insets
664 // FIXME: Care about the d->cursor_ flags to redraw if needed
665 Cursor old = d->cursor_;
667 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
669 d->cursor_.fixIfBroken();
673 Change const BufferView::getCurrentChange() const
675 if (!d->cursor_.selection())
676 return Change(Change::UNCHANGED);
678 DocIterator dit = d->cursor_.selectionBegin();
679 return dit.paragraph().lookupChange(dit.pos());
683 // this could be used elsewhere as well?
684 // FIXME: This does not work within mathed!
685 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
687 Point const p = getPos(dit);
690 if (p.y_ > workHeight())
696 void BufferView::bookmarkEditPosition()
698 // Don't eat cpu time for each keystroke
699 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
702 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
706 void BufferView::saveBookmark(unsigned int idx)
708 // tentatively save bookmark, id and pos will be used to
709 // acturately locate a bookmark in a 'live' lyx session.
710 // pit and pos will be updated with bottom level pit/pos
712 if (!buffer_.isInternal()) {
713 theSession().bookmarks().save(
715 d->cursor_.bottom().pit(),
716 d->cursor_.bottom().pos(),
717 d->cursor_.paragraph().id(),
722 // emit message signal.
723 message(_("Save bookmark"));
728 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
729 int top_id, pos_type top_pos)
731 bool success = false;
734 d->cursor_.clearSelection();
736 // if a valid par_id is given, try it first
737 // This is the case for a 'live' bookmark when unique paragraph ID
738 // is used to track bookmarks.
740 dit = buffer_.getParFromID(top_id);
742 dit.pos() = min(dit.paragraph().size(), top_pos);
743 // Some slices of the iterator may not be
744 // reachable (e.g. closed collapsable inset)
745 // so the dociterator may need to be
746 // shortened. Otherwise, setCursor may crash
747 // lyx when the cursor can not be set to these
749 size_t const n = dit.depth();
750 for (size_t i = 0; i < n; ++i)
751 if (!dit[i].inset().editable()) {
759 // if top_id == 0, or searching through top_id failed
760 // This is the case for a 'restored' bookmark when only bottom
761 // (document level) pit was saved. Because of this, bookmark
762 // restoration is inaccurate. If a bookmark was within an inset,
763 // it will be restored to the left of the outmost inset that contains
765 if (bottom_pit < int(buffer_.paragraphs().size())) {
766 dit = doc_iterator_begin(&buffer_);
768 dit.pit() = bottom_pit;
769 dit.pos() = min(bottom_pos, dit.paragraph().size());
774 // Note: only bottom (document) level pit is set.
776 // set the current font.
777 d->cursor_.setCurrentFont();
778 // To center the screen on this new position we need the
779 // paragraph position which is computed at draw() time.
780 // So we need a redraw!
781 buffer_.changed(false);
790 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
792 if (lyxrc.rtl_support) {
793 if (d->cursor_.real_current_font.isRightToLeft()) {
794 if (d->intl_.keymap == Intl::PRIMARY)
795 d->intl_.keyMapSec();
797 if (d->intl_.keymap == Intl::SECONDARY)
798 d->intl_.keyMapPrim();
802 d->intl_.getTransManager().translateAndInsert(c, t, cur);
806 int BufferView::workWidth() const
812 void BufferView::recenter()
814 showCursor(d->cursor_, true, true);
818 void BufferView::showCursor()
820 showCursor(d->cursor_, false, true);
824 void BufferView::showCursor(DocIterator const & dit,
825 bool recenter, bool update)
827 if (scrollToCursor(dit, recenter) && update) {
828 buffer_.changed(true);
829 updateHoveredInset();
834 void BufferView::scrollToCursor()
836 if (scrollToCursor(d->cursor_, false)) {
837 buffer_.changed(true);
838 updateHoveredInset();
843 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
845 // We are not properly started yet, delay until resizing is
850 LYXERR(Debug::SCROLLING, "recentering!");
852 CursorSlice const & bot = dit.bottom();
853 TextMetrics & tm = d->text_metrics_[bot.text()];
855 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
856 int bot_pit = bot.pit();
857 if (bot_pit > max_pit) {
858 // FIXME: Why does this happen?
859 LYXERR0("bottom pit is greater that max pit: "
860 << bot_pit << " > " << max_pit);
864 if (bot_pit == tm.first().first - 1)
865 tm.newParMetricsUp();
866 else if (bot_pit == tm.last().first + 1)
867 tm.newParMetricsDown();
869 if (tm.contains(bot_pit)) {
870 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
871 LASSERT(!pm.rows().empty(), /**/);
872 // FIXME: smooth scrolling doesn't work in mathed.
873 CursorSlice const & cs = dit.innerTextSlice();
874 int offset = coordOffset(dit).y_;
875 int ypos = pm.position() + offset;
876 Dimension const & row_dim =
877 pm.getRow(cs.pos(), dit.boundary()).dimension();
880 scrolled = scroll(ypos - height_/2);
882 // If the top part of the row falls of the screen, we scroll
883 // up to align the top of the row with the top of the screen.
884 else if (ypos - row_dim.ascent() < 0)
885 scrolled = scrollUp(-ypos + row_dim.ascent());
887 // If the bottom of the row falls of the screen, we scroll down.
888 // However, we have to be careful not to scroll that much that
889 // the top falls of the screen.
890 else if (ypos + row_dim.descent() > height_) {
891 int ynew = height_ - row_dim.descent();
892 if (ynew < row_dim.ascent())
893 ynew = row_dim.ascent();
894 int const scroll = ypos - ynew;
895 scrolled = scrollDown(scroll);
898 // else, nothing to do, the cursor is already visible so we just return.
899 return scrolled != 0;
902 // fix inline completion position
903 if (d->inlineCompletionPos_.fixIfBroken())
904 d->inlineCompletionPos_ = DocIterator();
906 tm.redoParagraph(bot_pit);
907 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
908 int offset = coordOffset(dit).y_;
910 d->anchor_pit_ = bot_pit;
911 CursorSlice const & cs = dit.innerTextSlice();
912 Dimension const & row_dim =
913 pm.getRow(cs.pos(), dit.boundary()).dimension();
916 d->anchor_ypos_ = height_/2;
917 else if (d->anchor_pit_ == 0)
918 d->anchor_ypos_ = offset + pm.ascent();
919 else if (d->anchor_pit_ == max_pit)
920 d->anchor_ypos_ = height_ - offset - row_dim.descent();
921 else if (offset > height_)
922 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
924 d->anchor_ypos_ = defaultRowHeight() * 2;
930 void BufferView::updateDocumentClass(DocumentClass const * const olddc)
932 message(_("Converting document to new document class..."));
934 StableDocIterator backcur(d->cursor_);
935 ErrorList & el = buffer_.errorList("Class Switch");
936 cap::switchBetweenClasses(
937 olddc, buffer_.params().documentClassPtr(),
938 static_cast<InsetText &>(buffer_.inset()), el);
940 setCursor(backcur.asDocIterator(&buffer_));
942 buffer_.errors("Class Switch");
945 /** Return the change status at cursor position, taking in account the
946 * status at each level of the document iterator (a table in a deleted
947 * footnote is deleted).
948 * When \param outer is true, the top slice is not looked at.
950 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
952 size_t const depth = dit.depth() - (outer ? 1 : 0);
954 for (size_t i = 0 ; i < depth ; ++i) {
955 CursorSlice const & slice = dit[i];
956 if (!slice.inset().inMathed()
957 && slice.pos() < slice.paragraph().size()) {
958 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
959 if (ch != Change::UNCHANGED)
963 return Change::UNCHANGED;
967 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
969 FuncCode const act = cmd.action();
971 // Can we use a readonly buffer?
972 if (buffer_.isReadonly()
973 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
974 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
975 flag.message(from_utf8(N_("Document is read-only")));
976 flag.setEnabled(false);
980 // Are we in a DELETED change-tracking region?
981 if (lookupChangeType(d->cursor_, true) == Change::DELETED
982 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
983 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
984 flag.message(from_utf8(N_("This portion of the document is deleted.")));
985 flag.setEnabled(false);
989 Cursor & cur = d->cursor_;
991 if (cur.getStatus(cmd, flag))
996 // FIXME: This is a bit problematic because we don't check if this is
997 // a document BufferView or not for these LFUNs. We probably have to
998 // dispatch both to currentBufferView() and, if that fails,
999 // to documentBufferView(); same as we do now for current Buffer and
1000 // document Buffer. Ideally those LFUN should go to Buffer as they
1001 // operate on the full Buffer and the cursor is only needed either for
1002 // an Undo record or to restore a cursor position. But we don't know
1003 // how to do that inside Buffer of course.
1004 case LFUN_BUFFER_PARAMS_APPLY:
1005 case LFUN_LAYOUT_MODULES_CLEAR:
1006 case LFUN_LAYOUT_MODULE_ADD:
1007 case LFUN_LAYOUT_RELOAD:
1008 case LFUN_TEXTCLASS_APPLY:
1009 case LFUN_TEXTCLASS_LOAD:
1010 flag.setEnabled(!buffer_.isReadonly());
1014 // We do not use the LyXAction flag for readonly because Undo sets the
1015 // buffer clean/dirty status by itself.
1016 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1019 // We do not use the LyXAction flag for readonly because Redo sets the
1020 // buffer clean/dirty status by itself.
1021 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1023 case LFUN_FILE_INSERT:
1024 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1025 case LFUN_FILE_INSERT_PLAINTEXT:
1026 case LFUN_BOOKMARK_SAVE:
1027 // FIXME: Actually, these LFUNS should be moved to Text
1028 flag.setEnabled(cur.inTexted());
1031 case LFUN_FONT_STATE:
1032 case LFUN_LABEL_INSERT:
1033 case LFUN_INFO_INSERT:
1034 case LFUN_PARAGRAPH_GOTO:
1035 case LFUN_NOTE_NEXT:
1036 case LFUN_REFERENCE_NEXT:
1037 case LFUN_WORD_FIND:
1038 case LFUN_WORD_FIND_FORWARD:
1039 case LFUN_WORD_FIND_BACKWARD:
1040 case LFUN_WORD_FINDADV:
1041 case LFUN_WORD_REPLACE:
1044 case LFUN_MARK_TOGGLE:
1045 case LFUN_SCREEN_RECENTER:
1046 case LFUN_SCREEN_SHOW_CURSOR:
1047 case LFUN_BIBTEX_DATABASE_ADD:
1048 case LFUN_BIBTEX_DATABASE_DEL:
1049 case LFUN_STATISTICS:
1050 case LFUN_BRANCH_ADD_INSERT:
1051 case LFUN_KEYMAP_OFF:
1052 case LFUN_KEYMAP_PRIMARY:
1053 case LFUN_KEYMAP_SECONDARY:
1054 case LFUN_KEYMAP_TOGGLE:
1055 flag.setEnabled(true);
1058 case LFUN_LABEL_GOTO: {
1059 flag.setEnabled(!cmd.argument().empty()
1060 || getInsetByCode<InsetRef>(cur, REF_CODE));
1064 case LFUN_CHANGES_TRACK:
1065 flag.setEnabled(true);
1066 flag.setOnOff(buffer_.params().trackChanges);
1069 case LFUN_CHANGES_OUTPUT:
1070 flag.setEnabled(true);
1071 flag.setOnOff(buffer_.params().outputChanges);
1074 case LFUN_CHANGES_MERGE:
1075 case LFUN_CHANGE_NEXT:
1076 case LFUN_CHANGE_PREVIOUS:
1077 case LFUN_ALL_CHANGES_ACCEPT:
1078 case LFUN_ALL_CHANGES_REJECT:
1079 // TODO: context-sensitive enabling of LFUNs
1080 // In principle, these command should only be enabled if there
1081 // is a change in the document. However, without proper
1082 // optimizations, this will inevitably result in poor performance.
1083 flag.setEnabled(true);
1086 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1087 flag.setOnOff(buffer_.params().compressed);
1091 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
1092 flag.setOnOff(buffer_.params().output_sync);
1096 case LFUN_SCREEN_UP:
1097 case LFUN_SCREEN_DOWN:
1099 case LFUN_SCREEN_UP_SELECT:
1100 case LFUN_SCREEN_DOWN_SELECT:
1101 case LFUN_INSET_FORALL:
1102 flag.setEnabled(true);
1105 case LFUN_LAYOUT_TABULAR:
1106 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1110 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1113 case LFUN_LAYOUT_PARAGRAPH:
1114 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1117 case LFUN_DIALOG_SHOW_NEW_INSET:
1118 // FIXME: this is wrong, but I do not understand the
1120 if (cur.inset().lyxCode() == CAPTION_CODE)
1121 return cur.inset().getStatus(cur, cmd, flag);
1122 // FIXME we should consider passthru paragraphs too.
1123 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1126 case LFUN_CITATION_INSERT: {
1127 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1128 // FIXME: This could turn in a recursive hell.
1129 // Shouldn't we use Buffer::getStatus() instead?
1130 flag.setEnabled(lyx::getStatus(fr).enabled());
1133 case LFUN_INSET_APPLY: {
1134 string const name = cmd.getArg(0);
1135 Inset * inset = editedInset(name);
1137 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1138 if (!inset->getStatus(cur, fr, flag)) {
1139 // Every inset is supposed to handle this
1140 LASSERT(false, break);
1143 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1144 flag = lyx::getStatus(fr);
1157 Inset * BufferView::editedInset(string const & name) const
1159 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1160 return it == d->edited_insets_.end() ? 0 : it->second;
1164 void BufferView::editInset(string const & name, Inset * inset)
1166 d->edited_insets_[name] = inset;
1170 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1172 //lyxerr << [ cmd = " << cmd << "]" << endl;
1174 // Make sure that the cached BufferView is correct.
1175 LYXERR(Debug::ACTION, " action[" << cmd.action() << ']'
1176 << " arg[" << to_utf8(cmd.argument()) << ']'
1177 << " x[" << cmd.x() << ']'
1178 << " y[" << cmd.y() << ']'
1179 << " button[" << cmd.button() << ']');
1181 string const argument = to_utf8(cmd.argument());
1182 Cursor & cur = d->cursor_;
1184 // Don't dispatch function that does not apply to internal buffers.
1185 if (buffer_.isInternal()
1186 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1189 // We'll set this back to false if need be.
1190 bool dispatched = true;
1191 buffer_.undo().beginUndoGroup();
1193 FuncCode const act = cmd.action();
1196 case LFUN_BUFFER_PARAMS_APPLY: {
1197 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1198 cur.recordUndoFullDocument();
1199 istringstream ss(to_utf8(cmd.argument()));
1202 int const unknown_tokens = buffer_.readHeader(lex);
1203 if (unknown_tokens != 0) {
1204 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1205 << unknown_tokens << " unknown token"
1206 << (unknown_tokens == 1 ? "" : "s"));
1208 updateDocumentClass(oldClass);
1210 // We are most certainly here because of a change in the document
1211 // It is then better to make sure that all dialogs are in sync with
1212 // current document settings.
1213 dr.screenUpdate(Update::Force | Update::FitCursor);
1214 dr.forceBufferUpdate();
1218 case LFUN_LAYOUT_MODULES_CLEAR: {
1219 DocumentClass const * const oldClass =
1220 buffer_.params().documentClassPtr();
1221 cur.recordUndoFullDocument();
1222 buffer_.params().clearLayoutModules();
1223 buffer_.params().makeDocumentClass();
1224 updateDocumentClass(oldClass);
1225 dr.screenUpdate(Update::Force);
1226 dr.forceBufferUpdate();
1230 case LFUN_LAYOUT_MODULE_ADD: {
1231 BufferParams const & params = buffer_.params();
1232 if (!params.moduleCanBeAdded(argument)) {
1233 LYXERR0("Module `" << argument <<
1234 "' cannot be added due to failed requirements or "
1235 "conflicts with installed modules.");
1238 DocumentClass const * const oldClass = params.documentClassPtr();
1239 cur.recordUndoFullDocument();
1240 buffer_.params().addLayoutModule(argument);
1241 buffer_.params().makeDocumentClass();
1242 updateDocumentClass(oldClass);
1243 dr.screenUpdate(Update::Force);
1244 dr.forceBufferUpdate();
1248 case LFUN_TEXTCLASS_APPLY: {
1249 // since this shortcircuits, the second call is made only if
1251 bool const success =
1252 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1253 LayoutFileList::get().load(argument, buffer_.filePath());
1255 docstring s = bformat(_("The document class `%1$s' "
1256 "could not be loaded."), from_utf8(argument));
1257 frontend::Alert::error(_("Could not load class"), s);
1261 LayoutFile const * old_layout = buffer_.params().baseClass();
1262 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1264 if (old_layout == new_layout)
1268 // Save the old, possibly modular, layout for use in conversion.
1269 DocumentClass const * const oldDocClass =
1270 buffer_.params().documentClassPtr();
1271 cur.recordUndoFullDocument();
1272 buffer_.params().setBaseClass(argument);
1273 buffer_.params().makeDocumentClass();
1274 updateDocumentClass(oldDocClass);
1275 dr.screenUpdate(Update::Force);
1276 dr.forceBufferUpdate();
1280 case LFUN_TEXTCLASS_LOAD: {
1281 // since this shortcircuits, the second call is made only if
1283 bool const success =
1284 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1285 LayoutFileList::get().load(argument, buffer_.filePath());
1287 docstring s = bformat(_("The document class `%1$s' "
1288 "could not be loaded."), from_utf8(argument));
1289 frontend::Alert::error(_("Could not load class"), s);
1294 case LFUN_LAYOUT_RELOAD: {
1295 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1296 LayoutFileIndex bc = buffer_.params().baseClassID();
1297 LayoutFileList::get().reset(bc);
1298 buffer_.params().setBaseClass(bc);
1299 buffer_.params().makeDocumentClass();
1300 updateDocumentClass(oldClass);
1301 dr.screenUpdate(Update::Force);
1302 dr.forceBufferUpdate();
1307 dr.setMessage(_("Undo"));
1308 cur.clearSelection();
1309 if (!cur.textUndo())
1310 dr.setMessage(_("No further undo information"));
1312 dr.screenUpdate(Update::Force | Update::FitCursor);
1313 dr.forceBufferUpdate();
1317 dr.setMessage(_("Redo"));
1318 cur.clearSelection();
1319 if (!cur.textRedo())
1320 dr.setMessage(_("No further redo information"));
1322 dr.screenUpdate(Update::Force | Update::FitCursor);
1323 dr.forceBufferUpdate();
1326 case LFUN_FONT_STATE:
1327 dr.setMessage(cur.currentState());
1330 case LFUN_BOOKMARK_SAVE:
1331 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1334 case LFUN_LABEL_GOTO: {
1335 docstring label = cmd.argument();
1336 if (label.empty()) {
1338 getInsetByCode<InsetRef>(cur, REF_CODE);
1340 label = inset->getParam("reference");
1341 // persistent=false: use temp_bookmark
1345 if (!label.empty()) {
1347 // at the moment, this is redundant, since gotoLabel will
1348 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1350 dr.screenUpdate(Update::Force | Update::FitCursor);
1355 case LFUN_PARAGRAPH_GOTO: {
1356 int const id = convert<int>(cmd.getArg(0));
1357 int const pos = convert<int>(cmd.getArg(1));
1359 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1360 b = theBufferList().next(b)) {
1362 DocIterator dit = b->getParFromID(id);
1364 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1368 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1369 << " found in buffer `"
1370 << b->absFileName() << "'.");
1372 if (b == &buffer_) {
1376 dr.screenUpdate(Update::Force | Update::FitCursor);
1378 // Switch to other buffer view and resend cmd
1379 lyx::dispatch(FuncRequest(
1380 LFUN_BUFFER_SWITCH, b->absFileName()));
1388 case LFUN_NOTE_NEXT:
1389 gotoInset(this, NOTE_CODE, false);
1392 case LFUN_REFERENCE_NEXT: {
1393 vector<InsetCode> tmp;
1394 tmp.push_back(LABEL_CODE);
1395 tmp.push_back(REF_CODE);
1396 gotoInset(this, tmp, true);
1400 case LFUN_CHANGES_TRACK:
1401 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1404 case LFUN_CHANGES_OUTPUT:
1405 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1406 if (buffer_.params().outputChanges) {
1407 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1408 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1409 LaTeXFeatures::isAvailable("xcolor");
1411 if (!dvipost && !xcolorulem) {
1412 Alert::warning(_("Changes not shown in LaTeX output"),
1413 _("Changes will not be highlighted in LaTeX output, "
1414 "because neither dvipost nor xcolor/ulem are installed.\n"
1415 "Please install these packages or redefine "
1416 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1417 } else if (!xcolorulem) {
1418 Alert::warning(_("Changes not shown in LaTeX output"),
1419 _("Changes will not be highlighted in LaTeX output "
1420 "when using pdflatex, because xcolor and ulem are not installed.\n"
1421 "Please install both packages or redefine "
1422 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1427 case LFUN_CHANGE_NEXT:
1428 findNextChange(this);
1429 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1430 dr.screenUpdate(Update::Force | Update::FitCursor);
1433 case LFUN_CHANGE_PREVIOUS:
1434 findPreviousChange(this);
1435 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1436 dr.screenUpdate(Update::Force | Update::FitCursor);
1439 case LFUN_CHANGES_MERGE:
1440 if (findNextChange(this) || findPreviousChange(this)) {
1441 dr.screenUpdate(Update::Force | Update::FitCursor);
1442 dr.forceBufferUpdate();
1443 showDialog("changes");
1447 case LFUN_ALL_CHANGES_ACCEPT:
1448 // select complete document
1450 cur.selHandle(true);
1451 buffer_.text().cursorBottom(cur);
1452 // accept everything in a single step to support atomic undo
1453 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1454 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1455 dr.screenUpdate(Update::Force | Update::FitCursor);
1456 dr.forceBufferUpdate();
1459 case LFUN_ALL_CHANGES_REJECT:
1460 // select complete document
1462 cur.selHandle(true);
1463 buffer_.text().cursorBottom(cur);
1464 // reject everything in a single step to support atomic undo
1465 // Note: reject does not work recursively; the user may have to repeat the operation
1466 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1467 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1468 dr.screenUpdate(Update::Force | Update::FitCursor);
1469 dr.forceBufferUpdate();
1472 case LFUN_WORD_FIND_FORWARD:
1473 case LFUN_WORD_FIND_BACKWARD: {
1474 static docstring last_search;
1475 docstring searched_string;
1477 if (!cmd.argument().empty()) {
1478 last_search = cmd.argument();
1479 searched_string = cmd.argument();
1481 searched_string = last_search;
1484 if (searched_string.empty())
1487 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1488 docstring const data =
1489 find2string(searched_string, true, false, fw);
1490 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1492 dr.screenUpdate(Update::Force | Update::FitCursor);
1496 case LFUN_WORD_FIND: {
1497 FuncRequest req = cmd;
1498 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1499 req = d->search_request_cache_;
1500 if (req.argument().empty()) {
1501 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1504 if (lyxfind(this, req))
1505 dr.screenUpdate(Update::Force | Update::FitCursor);
1507 message(_("String not found!"));
1508 d->search_request_cache_ = req;
1512 case LFUN_WORD_REPLACE: {
1513 bool has_deleted = false;
1514 if (cur.selection()) {
1515 DocIterator beg = cur.selectionBegin();
1516 DocIterator end = cur.selectionEnd();
1517 if (beg.pit() == end.pit()) {
1518 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1519 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1526 if (lyxreplace(this, cmd, has_deleted)) {
1527 dr.forceBufferUpdate();
1528 dr.screenUpdate(Update::Force | Update::FitCursor);
1533 case LFUN_WORD_FINDADV: {
1534 FindAndReplaceOptions opt;
1535 istringstream iss(to_utf8(cmd.argument()));
1537 if (findAdv(this, opt))
1538 dr.screenUpdate(Update::Force | Update::FitCursor);
1543 cur.clearSelection();
1544 dr.setMessage(from_utf8(N_("Mark off")));
1548 cur.clearSelection();
1550 dr.setMessage(from_utf8(N_("Mark on")));
1553 case LFUN_MARK_TOGGLE:
1554 cur.setSelection(false);
1557 dr.setMessage(from_utf8(N_("Mark removed")));
1560 dr.setMessage(from_utf8(N_("Mark set")));
1565 case LFUN_SCREEN_SHOW_CURSOR:
1569 case LFUN_SCREEN_RECENTER:
1573 case LFUN_BIBTEX_DATABASE_ADD: {
1574 Cursor tmpcur = cur;
1575 findInset(tmpcur, BIBTEX_CODE, false);
1576 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1579 if (inset->addDatabase(cmd.argument())) {
1580 buffer_.invalidateBibfileCache();
1581 dr.forceBufferUpdate();
1587 case LFUN_BIBTEX_DATABASE_DEL: {
1588 Cursor tmpcur = cur;
1589 findInset(tmpcur, BIBTEX_CODE, false);
1590 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1593 if (inset->delDatabase(cmd.argument())) {
1594 buffer_.invalidateBibfileCache();
1595 dr.forceBufferUpdate();
1601 case LFUN_STATISTICS: {
1602 DocIterator from, to;
1603 if (cur.selection()) {
1604 from = cur.selectionBegin();
1605 to = cur.selectionEnd();
1607 from = doc_iterator_begin(&buffer_);
1608 to = doc_iterator_end(&buffer_);
1610 int const words = countWords(from, to);
1611 int const chars = countChars(from, to, false);
1612 int const chars_blanks = countChars(from, to, true);
1614 if (cur.selection())
1615 message = _("Statistics for the selection:");
1617 message = _("Statistics for the document:");
1620 message += bformat(_("%1$d words"), words);
1622 message += _("One word");
1624 if (chars_blanks != 1)
1625 message += bformat(_("%1$d characters (including blanks)"),
1628 message += _("One character (including blanks)");
1631 message += bformat(_("%1$d characters (excluding blanks)"),
1634 message += _("One character (excluding blanks)");
1636 Alert::information(_("Statistics"), message);
1640 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1641 // turn compression on/off
1642 buffer_.params().compressed = !buffer_.params().compressed;
1645 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
1646 buffer_.params().output_sync = !buffer_.params().output_sync;
1649 case LFUN_SCREEN_UP:
1650 case LFUN_SCREEN_DOWN: {
1651 Point p = getPos(cur);
1652 // This code has been commented out to enable to scroll down a
1653 // document, even if there are large insets in it (see bug #5465).
1654 /*if (p.y_ < 0 || p.y_ > height_) {
1655 // The cursor is off-screen so recenter before proceeding.
1659 int const scrolled = scroll(act == LFUN_SCREEN_UP
1660 ? -height_ : height_);
1661 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1663 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1664 p = Point(width_, height_);
1666 bool const in_texted = cur.inTexted();
1668 buffer_.changed(true);
1669 updateHoveredInset();
1671 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1672 true, act == LFUN_SCREEN_UP);
1673 //FIXME: what to do with cur.x_target()?
1674 bool update = in_texted && cur.bv().checkDepm(cur, old);
1677 dr.screenUpdate(Update::Force | Update::FitCursor);
1678 dr.forceBufferUpdate();
1685 dr.forceBufferUpdate();
1688 case LFUN_SCREEN_UP_SELECT: {
1689 cur.selHandle(true);
1690 if (isTopScreen()) {
1691 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1695 int y = getPos(cur).y_;
1696 int const ymin = y - height_ + defaultRowHeight();
1697 while (y > ymin && cur.up())
1701 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1705 case LFUN_SCREEN_DOWN_SELECT: {
1706 cur.selHandle(true);
1707 if (isBottomScreen()) {
1708 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1712 int y = getPos(cur).y_;
1713 int const ymax = y + height_ - defaultRowHeight();
1714 while (y < ymax && cur.down())
1718 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1723 // This would be in Buffer class if only Cursor did not
1724 // require a bufferview
1725 case LFUN_INSET_FORALL: {
1726 docstring const name = from_utf8(cmd.getArg(0));
1727 string const commandstr = cmd.getLongArg(1);
1728 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1730 // an arbitrary number to limit number of iterations
1731 const int max_iter = 10000;
1733 Cursor & cur = d->cursor_;
1734 Cursor const savecur = cur;
1736 if (!cur.nextInset())
1738 cur.beginUndoGroup();
1739 while(cur && iterations < max_iter) {
1740 Inset * ins = cur.nextInset();
1743 docstring insname = ins->name();
1744 while (!insname.empty()) {
1745 if (insname == name || name == from_utf8("*")) {
1747 lyx::dispatch(fr, dr);
1751 size_t const i = insname.rfind(':');
1752 if (i == string::npos)
1754 insname = insname.substr(0, i);
1761 dr.screenUpdate(Update::Force);
1762 dr.forceBufferUpdate();
1764 if (iterations >= max_iter) {
1766 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1768 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1773 case LFUN_BRANCH_ADD_INSERT: {
1774 docstring branch_name = from_utf8(cmd.getArg(0));
1775 if (branch_name.empty())
1776 if (!Alert::askForText(branch_name, _("Branch name")) ||
1777 branch_name.empty())
1780 DispatchResult drtmp;
1781 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1782 if (drtmp.error()) {
1783 Alert::warning(_("Branch already exists"), drtmp.message());
1786 BranchList & branch_list = buffer_.params().branchlist();
1787 vector<docstring> const branches =
1788 getVectorFromString(branch_name, branch_list.separator());
1789 for (vector<docstring>::const_iterator it = branches.begin();
1790 it != branches.end(); ++it) {
1792 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1797 case LFUN_KEYMAP_OFF:
1798 getIntl().keyMapOn(false);
1801 case LFUN_KEYMAP_PRIMARY:
1802 getIntl().keyMapPrim();
1805 case LFUN_KEYMAP_SECONDARY:
1806 getIntl().keyMapSec();
1809 case LFUN_KEYMAP_TOGGLE:
1810 getIntl().toggleKeyMap();
1813 case LFUN_DIALOG_SHOW_NEW_INSET: {
1814 string const name = cmd.getArg(0);
1815 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1816 if (decodeInsetParam(name, data, buffer_))
1817 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1819 lyxerr << "Inset type '" << name <<
1820 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1824 case LFUN_CITATION_INSERT: {
1825 if (argument.empty()) {
1826 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1829 // we can have one optional argument, delimited by '|'
1830 // citation-insert <key>|<text_before>
1831 // this should be enhanced to also support text_after
1832 // and citation style
1833 string arg = argument;
1835 if (contains(argument, "|")) {
1836 arg = token(argument, '|', 0);
1837 opt1 = token(argument, '|', 1);
1839 InsetCommandParams icp(CITE_CODE);
1840 icp["key"] = from_utf8(arg);
1842 icp["before"] = from_utf8(opt1);
1843 string icstr = InsetCommand::params2string("citation", icp);
1844 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1849 case LFUN_INSET_APPLY: {
1850 string const name = cmd.getArg(0);
1851 Inset * inset = editedInset(name);
1853 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1857 // put cursor in front of inset.
1858 if (!setCursorFromInset(inset)) {
1859 LASSERT(false, break);
1862 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1863 inset->dispatch(cur, fr);
1864 dr.screenUpdate(cur.result().screenUpdate());
1865 if (cur.result().needBufferUpdate())
1866 dr.forceBufferUpdate();
1875 buffer_.undo().endUndoGroup();
1876 dr.dispatched(dispatched);
1881 docstring const BufferView::requestSelection()
1883 Cursor & cur = d->cursor_;
1885 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1886 if (!cur.selection()) {
1887 d->xsel_cache_.set = false;
1891 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1892 if (!d->xsel_cache_.set ||
1893 cur.top() != d->xsel_cache_.cursor ||
1894 cur.realAnchor().top() != d->xsel_cache_.anchor)
1896 d->xsel_cache_.cursor = cur.top();
1897 d->xsel_cache_.anchor = cur.realAnchor().top();
1898 d->xsel_cache_.set = cur.selection();
1899 return cur.selectionAsString(false);
1905 void BufferView::clearSelection()
1907 d->cursor_.clearSelection();
1908 // Clear the selection buffer. Otherwise a subsequent
1909 // middle-mouse-button paste would use the selection buffer,
1910 // not the more current external selection.
1911 cap::clearSelection();
1912 d->xsel_cache_.set = false;
1913 // The buffer did not really change, but this causes the
1914 // redraw we need because we cleared the selection above.
1915 buffer_.changed(false);
1919 void BufferView::resize(int width, int height)
1921 // Update from work area
1925 // Clear the paragraph height cache.
1926 d->par_height_.clear();
1927 // Redo the metrics.
1932 Inset const * BufferView::getCoveringInset(Text const & text,
1935 TextMetrics & tm = d->text_metrics_[&text];
1936 Inset * inset = tm.checkInsetHit(x, y);
1940 if (!inset->descendable(*this))
1941 // No need to go further down if the inset is not
1945 size_t cell_number = inset->nargs();
1946 // Check all the inner cell.
1947 for (size_t i = 0; i != cell_number; ++i) {
1948 Text const * inner_text = inset->getText(i);
1951 Inset const * inset_deeper =
1952 getCoveringInset(*inner_text, x, y);
1954 return inset_deeper;
1962 void BufferView::updateHoveredInset() const
1964 // Get inset under mouse, if there is one.
1965 int const x = d->mouse_position_cache_.x_;
1966 int const y = d->mouse_position_cache_.y_;
1967 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
1969 d->clickable_inset_ = covering_inset && covering_inset->clickable(x, y);
1971 if (covering_inset == d->last_inset_)
1972 // Same inset, no need to do anything...
1975 bool need_redraw = false;
1976 if (d->last_inset_) {
1977 // Remove the hint on the last hovered inset (if any).
1978 need_redraw |= d->last_inset_->setMouseHover(this, false);
1982 // const_cast because of setMouseHover().
1983 Inset * inset = const_cast<Inset *>(covering_inset);
1984 if (inset && inset->setMouseHover(this, true)) {
1986 // Only the insets that accept the hover state, do
1987 // clear the last_inset_, so only set the last_inset_
1988 // member if the hovered setting is accepted.
1989 d->last_inset_ = inset;
1993 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1994 << d->mouse_position_cache_.x_ << ", "
1995 << d->mouse_position_cache_.y_ << ")");
1997 d->update_strategy_ = DecorationUpdate;
1999 // This event (moving without mouse click) is not passed further.
2000 // This should be changed if it is further utilized.
2001 buffer_.changed(false);
2006 void BufferView::clearLastInset(Inset * inset) const
2008 if (d->last_inset_ != inset) {
2009 LYXERR0("Wrong last_inset!");
2010 LASSERT(false, /**/);
2016 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2018 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2020 // This is only called for mouse related events including
2021 // LFUN_FILE_OPEN generated by drag-and-drop.
2022 FuncRequest cmd = cmd0;
2024 Cursor old = cursor();
2026 cur.push(buffer_.inset());
2027 cur.setSelection(d->cursor_.selection());
2029 // Either the inset under the cursor or the
2030 // surrounding Text will handle this event.
2032 // make sure we stay within the screen...
2033 cmd.set_y(min(max(cmd.y(), -1), height_));
2035 d->mouse_position_cache_.x_ = cmd.x();
2036 d->mouse_position_cache_.y_ = cmd.y();
2038 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2039 updateHoveredInset();
2043 // Build temporary cursor.
2044 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2046 // Put anchor at the same position.
2049 cur.beginUndoGroup();
2051 // Try to dispatch to an non-editable inset near this position
2052 // via the temp cursor. If the inset wishes to change the real
2053 // cursor it has to do so explicitly by using
2054 // cur.bv().cursor() = cur; (or similar)
2056 inset->dispatch(cur, cmd);
2058 // Now dispatch to the temporary cursor. If the real cursor should
2059 // be modified, the inset's dispatch has to do so explicitly.
2060 if (!inset || !cur.result().dispatched())
2065 // Notify left insets
2068 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2070 cursor().fixIfBroken();
2073 // Do we have a selection?
2074 theSelection().haveSelection(cursor().selection());
2076 // If the command has been dispatched,
2077 if (cur.result().dispatched() || cur.result().screenUpdate())
2078 processUpdateFlags(cur.result().screenUpdate());
2082 void BufferView::lfunScroll(FuncRequest const & cmd)
2084 string const scroll_type = cmd.getArg(0);
2085 int scroll_step = 0;
2086 if (scroll_type == "line")
2087 scroll_step = d->scrollbarParameters_.single_step;
2088 else if (scroll_type == "page")
2089 scroll_step = d->scrollbarParameters_.page_step;
2092 string const scroll_quantity = cmd.getArg(1);
2093 if (scroll_quantity == "up")
2094 scrollUp(scroll_step);
2095 else if (scroll_quantity == "down")
2096 scrollDown(scroll_step);
2098 int const scroll_value = convert<int>(scroll_quantity);
2100 scroll(scroll_step * scroll_value);
2102 buffer_.changed(true);
2103 updateHoveredInset();
2107 int BufferView::minVisiblePart()
2109 return 2 * defaultRowHeight();
2113 int BufferView::scroll(int y)
2116 return scrollDown(y);
2118 return scrollUp(-y);
2123 int BufferView::scrollDown(int offset)
2125 Text * text = &buffer_.text();
2126 TextMetrics & tm = d->text_metrics_[text];
2127 int const ymax = height_ + offset;
2129 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2130 int bottom_pos = last.second->position() + last.second->descent();
2131 if (lyxrc.scroll_below_document)
2132 bottom_pos += height_ - minVisiblePart();
2133 if (last.first + 1 == int(text->paragraphs().size())) {
2134 if (bottom_pos <= height_)
2136 offset = min(offset, bottom_pos - height_);
2139 if (bottom_pos > ymax)
2141 tm.newParMetricsDown();
2143 d->anchor_ypos_ -= offset;
2148 int BufferView::scrollUp(int offset)
2150 Text * text = &buffer_.text();
2151 TextMetrics & tm = d->text_metrics_[text];
2152 int ymin = - offset;
2154 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2155 int top_pos = first.second->position() - first.second->ascent();
2156 if (first.first == 0) {
2159 offset = min(offset, - top_pos);
2164 tm.newParMetricsUp();
2166 d->anchor_ypos_ += offset;
2171 void BufferView::setCursorFromRow(int row)
2176 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2180 buffer_.text().setCursor(d->cursor_, 0, 0);
2182 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
2187 bool BufferView::setCursorFromInset(Inset const * inset)
2189 // are we already there?
2190 if (cursor().nextInset() == inset)
2193 // Inset is not at cursor position. Find it in the document.
2196 while (cur && cur.nextInset() != inset)
2207 void BufferView::gotoLabel(docstring const & label)
2209 ListOfBuffers bufs = buffer().allRelatives();
2210 ListOfBuffers::iterator it = bufs.begin();
2211 for (; it != bufs.end(); ++it) {
2212 Buffer const * buf = *it;
2215 Toc & toc = buf->tocBackend().toc("label");
2216 TocIterator toc_it = toc.begin();
2217 TocIterator end = toc.end();
2218 for (; toc_it != end; ++toc_it) {
2219 if (label == toc_it->str()) {
2220 lyx::dispatch(toc_it->action());
2228 TextMetrics const & BufferView::textMetrics(Text const * t) const
2230 return const_cast<BufferView *>(this)->textMetrics(t);
2234 TextMetrics & BufferView::textMetrics(Text const * t)
2236 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2237 if (tmc_it == d->text_metrics_.end()) {
2238 tmc_it = d->text_metrics_.insert(
2239 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2241 return tmc_it->second;
2245 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2248 return textMetrics(t).parMetrics(pit);
2252 int BufferView::workHeight() const
2258 void BufferView::setCursor(DocIterator const & dit)
2261 size_t const n = dit.depth();
2262 for (size_t i = 0; i < n; ++i)
2263 dit[i].inset().edit(d->cursor_, true);
2265 d->cursor_.setCursor(dit);
2266 d->cursor_.setSelection(false);
2270 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2272 // Would be wrong to delete anything if we have a selection.
2273 if (cur.selection())
2276 bool need_anchor_change = false;
2277 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2278 need_anchor_change);
2280 if (need_anchor_change)
2288 cur.forceBufferUpdate();
2289 buffer_.changed(true);
2294 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2296 LASSERT(&cur.bv() == this, /**/);
2299 // this event will clear selection so we save selection for
2300 // persistent selection
2301 cap::saveSelection(cursor());
2303 d->cursor_.macroModeClose();
2305 // Has the cursor just left the inset?
2306 bool leftinset = (&d->cursor_.inset() != &cur.inset());
2308 d->cursor_.fixIfBroken();
2310 // FIXME: shift-mouse selection doesn't work well across insets.
2311 bool do_selection = select && &d->cursor_.normalAnchor().inset() == &cur.inset();
2313 // do the dEPM magic if needed
2314 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2315 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2316 // the leftinset bool would not be necessary (badcursor instead).
2317 bool update = leftinset;
2318 if (!do_selection && d->cursor_.inTexted())
2319 update |= checkDepm(cur, d->cursor_);
2322 d->cursor_.resetAnchor();
2323 d->cursor_.setCursor(cur);
2324 d->cursor_.boundary(cur.boundary());
2326 d->cursor_.setSelection();
2328 d->cursor_.clearSelection();
2330 d->cursor_.finishUndo();
2331 d->cursor_.setCurrentFont();
2333 cur.forceBufferUpdate();
2338 void BufferView::putSelectionAt(DocIterator const & cur,
2339 int length, bool backwards)
2341 d->cursor_.clearSelection();
2347 d->cursor_.pos() += length;
2348 d->cursor_.setSelection(d->cursor_, -length);
2350 d->cursor_.setSelection(d->cursor_, length);
2355 Cursor & BufferView::cursor()
2361 Cursor const & BufferView::cursor() const
2367 pit_type BufferView::anchor_ref() const
2369 return d->anchor_pit_;
2373 bool BufferView::singleParUpdate()
2375 Text & buftext = buffer_.text();
2376 pit_type const bottom_pit = d->cursor_.bottom().pit();
2377 TextMetrics & tm = textMetrics(&buftext);
2378 int old_height = tm.parMetrics(bottom_pit).height();
2380 // make sure inline completion pointer is ok
2381 if (d->inlineCompletionPos_.fixIfBroken())
2382 d->inlineCompletionPos_ = DocIterator();
2384 // In Single Paragraph mode, rebreak only
2385 // the (main text, not inset!) paragraph containing the cursor.
2386 // (if this paragraph contains insets etc., rebreaking will
2387 // recursively descend)
2388 tm.redoParagraph(bottom_pit);
2389 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2390 if (pm.height() != old_height)
2391 // Paragraph height has changed so we cannot proceed to
2392 // the singlePar optimisation.
2395 d->update_strategy_ = SingleParUpdate;
2397 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2398 << " y2: " << pm.position() + pm.descent()
2399 << " pit: " << bottom_pit
2400 << " singlepar: 1");
2405 void BufferView::updateMetrics()
2407 if (height_ == 0 || width_ == 0)
2410 Text & buftext = buffer_.text();
2411 pit_type const npit = int(buftext.paragraphs().size());
2413 // Clear out the position cache in case of full screen redraw,
2414 d->coord_cache_.clear();
2416 // Clear out paragraph metrics to avoid having invalid metrics
2417 // in the cache from paragraphs not relayouted below
2418 // The complete text metrics will be redone.
2419 d->text_metrics_.clear();
2421 TextMetrics & tm = textMetrics(&buftext);
2423 // make sure inline completion pointer is ok
2424 if (d->inlineCompletionPos_.fixIfBroken())
2425 d->inlineCompletionPos_ = DocIterator();
2427 if (d->anchor_pit_ >= npit)
2428 // The anchor pit must have been deleted...
2429 d->anchor_pit_ = npit - 1;
2431 // Rebreak anchor paragraph.
2432 tm.redoParagraph(d->anchor_pit_);
2433 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2436 if (d->anchor_pit_ == 0) {
2437 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2439 // Complete buffer visible? Then it's easy.
2440 if (scrollRange == 0)
2441 d->anchor_ypos_ = anchor_pm.ascent();
2443 // FIXME: Some clever handling needed to show
2444 // the _first_ paragraph up to the top if the cursor is
2445 // in the first line.
2447 anchor_pm.setPosition(d->anchor_ypos_);
2449 LYXERR(Debug::PAINTING, "metrics: "
2450 << " anchor pit = " << d->anchor_pit_
2451 << " anchor ypos = " << d->anchor_ypos_);
2453 // Redo paragraphs above anchor if necessary.
2454 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2455 // We are now just above the anchor paragraph.
2456 pit_type pit1 = d->anchor_pit_ - 1;
2457 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2458 tm.redoParagraph(pit1);
2459 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2461 // Save the paragraph position in the cache.
2466 // Redo paragraphs below the anchor if necessary.
2467 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2468 // We are now just below the anchor paragraph.
2469 pit_type pit2 = d->anchor_pit_ + 1;
2470 for (; pit2 < npit && y2 <= height_; ++pit2) {
2471 tm.redoParagraph(pit2);
2472 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2474 // Save the paragraph position in the cache.
2479 LYXERR(Debug::PAINTING, "Metrics: "
2480 << " anchor pit = " << d->anchor_pit_
2481 << " anchor ypos = " << d->anchor_ypos_
2484 << " pit1 = " << pit1
2485 << " pit2 = " << pit2);
2487 d->update_strategy_ = FullScreenUpdate;
2489 if (lyxerr.debugging(Debug::WORKAREA)) {
2490 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2491 d->coord_cache_.dump();
2496 void BufferView::insertLyXFile(FileName const & fname)
2498 LASSERT(d->cursor_.inTexted(), /**/);
2500 // Get absolute path of file and add ".lyx"
2501 // to the filename if necessary
2502 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2504 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2505 // emit message signal.
2506 message(bformat(_("Inserting document %1$s..."), disp_fn));
2509 Buffer buf("", false);
2510 if (buf.loadLyXFile(filename) == Buffer::ReadSuccess) {
2511 ErrorList & el = buffer_.errorList("Parse");
2512 // Copy the inserted document error list into the current buffer one.
2513 el = buf.errorList("Parse");
2514 buffer_.undo().recordUndo(d->cursor_);
2515 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2516 buf.params().documentClassPtr(), el);
2517 res = _("Document %1$s inserted.");
2519 res = _("Could not insert document %1$s");
2522 buffer_.changed(true);
2523 // emit message signal.
2524 message(bformat(res, disp_fn));
2525 buffer_.errors("Parse");
2529 Point BufferView::coordOffset(DocIterator const & dit) const
2535 // Addup contribution of nested insets, from inside to outside,
2536 // keeping the outer paragraph for a special handling below
2537 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2538 CursorSlice const & sl = dit[i];
2542 // get relative position inside sl.inset()
2543 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2545 // Make relative position inside of the edited inset relative to sl.inset()
2549 // In case of an RTL inset, the edited inset will be positioned to the left
2552 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2553 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2558 // remember width for the case that sl.inset() is positioned in an RTL inset
2559 if (i && dit[i - 1].text()) {
2560 // If this Inset is inside a Text Inset, retrieve the Dimension
2561 // from the containing text instead of using Inset::dimension() which
2562 // might not be implemented.
2563 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2564 // elimination of Inset::dim_ cache. This coordOffset() method needs
2565 // to be rewritten in light of the new design.
2566 Dimension const & dim = parMetrics(dit[i - 1].text(),
2567 dit[i - 1].pit()).insetDimension(&sl.inset());
2570 Dimension const dim = sl.inset().dimension(*this);
2574 //lyxerr << "Cursor::getPos, i: "
2575 // << i << " x: " << xx << " y: " << y << endl;
2578 // Add contribution of initial rows of outermost paragraph
2579 CursorSlice const & sl = dit[0];
2580 TextMetrics const & tm = textMetrics(sl.text());
2581 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2582 LASSERT(!pm.rows().empty(), /**/);
2583 y -= pm.rows()[0].ascent();
2585 // FIXME: document this mess
2587 if (sl.pos() > 0 && dit.depth() == 1) {
2589 if (pos && dit.boundary())
2591 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2592 rend = pm.pos2row(pos);
2594 rend = pm.pos2row(sl.pos());
2596 size_t rend = pm.pos2row(sl.pos());
2598 for (size_t rit = 0; rit != rend; ++rit)
2599 y += pm.rows()[rit].height();
2600 y += pm.rows()[rend].ascent();
2602 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2604 // Make relative position from the nested inset now bufferview absolute.
2605 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2608 // In the RTL case place the nested inset at the left of the cursor in
2609 // the outer paragraph
2610 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2611 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2619 Point BufferView::getPos(DocIterator const & dit) const
2621 if (!paragraphVisible(dit))
2622 return Point(-1, -1);
2624 CursorSlice const & bot = dit.bottom();
2625 TextMetrics const & tm = textMetrics(bot.text());
2627 // offset from outer paragraph
2628 Point p = coordOffset(dit);
2629 p.y_ += tm.parMetrics(bot.pit()).position();
2634 bool BufferView::paragraphVisible(DocIterator const & dit) const
2636 CursorSlice const & bot = dit.bottom();
2637 TextMetrics const & tm = textMetrics(bot.text());
2639 return tm.contains(bot.pit());
2643 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2645 Cursor const & cur = cursor();
2646 Font const font = cur.getFont();
2647 frontend::FontMetrics const & fm = theFontMetrics(font);
2648 int const asc = fm.maxAscent();
2649 int const des = fm.maxDescent();
2656 bool BufferView::cursorInView(Point const & p, int h) const
2658 Cursor const & cur = cursor();
2659 // does the cursor touch the screen ?
2660 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2666 void BufferView::draw(frontend::Painter & pain)
2668 if (height_ == 0 || width_ == 0)
2670 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2672 Text & text = buffer_.text();
2673 TextMetrics const & tm = d->text_metrics_[&text];
2674 int const y = tm.first().second->position();
2675 PainterInfo pi(this, pain);
2677 switch (d->update_strategy_) {
2679 case NoScreenUpdate:
2680 // If no screen painting is actually needed, only some the different
2681 // coordinates of insets and paragraphs needs to be updated.
2682 pi.full_repaint = true;
2683 pi.pain.setDrawingEnabled(false);
2687 case SingleParUpdate:
2688 pi.full_repaint = false;
2689 // In general, only the current row of the outermost paragraph
2690 // will be redrawn. Particular cases where selection spans
2691 // multiple paragraph are correctly detected in TextMetrics.
2695 case DecorationUpdate:
2696 // FIXME: We should also distinguish DecorationUpdate to avoid text
2697 // drawing if possible. This is not possible to do easily right now
2698 // because of the single backing pixmap.
2700 case FullScreenUpdate:
2701 // The whole screen, including insets, will be refreshed.
2702 pi.full_repaint = true;
2704 // Clear background.
2705 pain.fillRectangle(0, 0, width_, height_,
2706 pi.backgroundColor(&buffer_.inset()));
2711 // and possibly grey out below
2712 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2713 int const y2 = lastpm.second->position() + lastpm.second->descent();
2716 Color color = buffer().isInternal()
2717 ? Color_background : Color_bottomarea;
2718 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2722 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2724 // The scrollbar needs an update.
2727 // Normalize anchor for next time
2728 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2729 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2730 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2731 ParagraphMetrics const & pm = tm.parMetrics(pit);
2732 if (pm.position() + pm.descent() > 0) {
2733 d->anchor_pit_ = pit;
2734 d->anchor_ypos_ = pm.position();
2738 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2739 << " anchor ypos = " << d->anchor_ypos_);
2743 void BufferView::message(docstring const & msg)
2746 d->gui_->message(msg);
2750 void BufferView::showDialog(string const & name)
2753 d->gui_->showDialog(name, string());
2757 void BufferView::showDialog(string const & name,
2758 string const & data, Inset * inset)
2761 d->gui_->showDialog(name, data, inset);
2765 void BufferView::updateDialog(string const & name, string const & data)
2768 d->gui_->updateDialog(name, data);
2772 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2778 // FIXME: Move this out of BufferView again
2779 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2781 if (!fname.isReadableFile()) {
2782 docstring const error = from_ascii(strerror(errno));
2783 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2784 docstring const text =
2785 bformat(_("Could not read the specified document\n"
2786 "%1$s\ndue to the error: %2$s"), file, error);
2787 Alert::error(_("Could not read file"), text);
2791 if (!fname.isReadableFile()) {
2792 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2793 docstring const text =
2794 bformat(_("%1$s\n is not readable."), file);
2795 Alert::error(_("Could not open file"), text);
2799 // FIXME UNICODE: We don't know the encoding of the file
2800 docstring file_content = fname.fileContents("UTF-8");
2801 if (file_content.empty()) {
2802 Alert::error(_("Reading not UTF-8 encoded file"),
2803 _("The file is not UTF-8 encoded.\n"
2804 "It will be read as local 8Bit-encoded.\n"
2805 "If this does not give the correct result\n"
2806 "then please change the encoding of the file\n"
2807 "to UTF-8 with a program other than LyX.\n"));
2808 file_content = fname.fileContents("local8bit");
2811 return normalize_c(file_content);
2815 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2817 docstring const tmpstr = contentsOfPlaintextFile(f);
2822 Cursor & cur = cursor();
2823 cap::replaceSelection(cur);
2824 buffer_.undo().recordUndo(cur);
2826 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2828 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2830 buffer_.changed(true);
2834 docstring const & BufferView::inlineCompletion() const
2836 return d->inlineCompletion_;
2840 size_t const & BufferView::inlineCompletionUniqueChars() const
2842 return d->inlineCompletionUniqueChars_;
2846 DocIterator const & BufferView::inlineCompletionPos() const
2848 return d->inlineCompletionPos_;
2852 bool samePar(DocIterator const & a, DocIterator const & b)
2854 if (a.empty() && b.empty())
2856 if (a.empty() || b.empty())
2858 if (a.depth() != b.depth())
2860 return &a.innerParagraph() == &b.innerParagraph();
2864 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2865 docstring const & completion, size_t uniqueChars)
2867 uniqueChars = min(completion.size(), uniqueChars);
2868 bool changed = d->inlineCompletion_ != completion
2869 || d->inlineCompletionUniqueChars_ != uniqueChars;
2870 bool singlePar = true;
2871 d->inlineCompletion_ = completion;
2872 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2874 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2877 DocIterator const & old = d->inlineCompletionPos_;
2879 //lyxerr << "inlineCompletionPos changed" << std::endl;
2880 // old or pos are in another paragraph?
2881 if ((!samePar(cur, pos) && !pos.empty())
2882 || (!samePar(cur, old) && !old.empty())) {
2884 //lyxerr << "different paragraph" << std::endl;
2886 d->inlineCompletionPos_ = pos;
2891 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
2892 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2894 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
2899 bool BufferView::clickableInset() const
2901 return d->clickable_inset_;