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), mouse_position_cache_(),
224 bookmark_edit_position_(-1), gui_(0)
228 ScrollbarParameters scrollbarParameters_;
230 ScreenUpdateStrategy update_strategy_;
232 CoordCache coord_cache_;
234 /// Estimated average par height for scrollbar.
236 /// this is used to handle XSelection events in the right manner.
245 pit_type anchor_pit_;
249 vector<int> par_height_;
252 DocIterator inlineCompletionPos_;
254 docstring inlineCompletion_;
256 size_t inlineCompletionUniqueChars_;
258 /// keyboard mapping object.
261 /// last visited inset.
262 /** kept to send setMouseHover(false).
263 * Not owned, so don't delete.
267 /// position of the mouse at the time of the last mouse move
268 /// This is used to update the hovering status of inset in
269 /// cases where the buffer is scrolled, but the mouse didn't move.
270 Point mouse_position_cache_;
272 // cache for id of the paragraph which was edited the last time
273 int bookmark_edit_position_;
275 mutable TextMetricsCache text_metrics_;
278 /** Not owned, so don't delete.
280 frontend::GuiBufferViewDelegate * gui_;
282 /// Cache for Find Next
283 FuncRequest search_request_cache_;
286 map<string, Inset *> edited_insets_;
290 BufferView::BufferView(Buffer & buf)
291 : width_(0), height_(0), full_screen_(false), buffer_(buf),
292 d(new Private(*this))
294 d->xsel_cache_.set = false;
295 d->intl_.initKeyMapper(lyxrc.use_kbmap);
297 d->cursor_.setBuffer(&buf);
298 d->cursor_.push(buffer_.inset());
299 d->cursor_.resetAnchor();
300 d->cursor_.setCurrentFont();
302 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
303 thePreviews().generateBufferPreviews(buffer_);
307 BufferView::~BufferView()
309 // current buffer is going to be switched-off, save cursor pos
310 // Ideally, the whole cursor stack should be saved, but session
311 // currently can only handle bottom (whole document) level pit and pos.
312 // That is to say, if a cursor is in a nested inset, it will be
313 // restore to the left of the top level inset.
314 LastFilePosSection::FilePos fp;
315 fp.pit = d->cursor_.bottom().pit();
316 fp.pos = d->cursor_.bottom().pos();
317 theSession().lastFilePos().save(buffer_.fileName(), fp);
320 d->last_inset_->setMouseHover(this, false);
326 int BufferView::rightMargin() const
328 // The additional test for the case the outliner is opened.
330 !lyxrc.full_screen_limit ||
331 width_ < lyxrc.full_screen_width + 20)
334 return (width_ - lyxrc.full_screen_width) / 2;
338 int BufferView::leftMargin() const
340 return rightMargin();
344 bool BufferView::isTopScreen() const
346 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
350 bool BufferView::isBottomScreen() const
352 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
356 Intl & BufferView::getIntl()
362 Intl const & BufferView::getIntl() const
368 CoordCache & BufferView::coordCache()
370 return d->coord_cache_;
374 CoordCache const & BufferView::coordCache() const
376 return d->coord_cache_;
380 Buffer & BufferView::buffer()
386 Buffer const & BufferView::buffer() const
392 bool BufferView::fitCursor()
394 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
395 frontend::FontMetrics const & fm =
396 theFontMetrics(d->cursor_.getFont().fontInfo());
397 int const asc = fm.maxAscent();
398 int const des = fm.maxDescent();
399 Point const p = getPos(d->cursor_);
400 if (p.y_ - asc >= 0 && p.y_ + des < height_)
407 void BufferView::processUpdateFlags(Update::flags flags)
409 // This is close to a hot-path.
410 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
411 << "[fitcursor = " << (flags & Update::FitCursor)
412 << ", forceupdate = " << (flags & Update::Force)
413 << ", singlepar = " << (flags & Update::SinglePar)
414 << "] buffer: " << &buffer_);
416 // FIXME Does this really need doing here? It's done in updateBuffer, and
417 // if the Buffer doesn't need updating, then do the macros?
418 buffer_.updateMacros();
420 // Now do the first drawing step if needed. This consists on updating
421 // the CoordCache in updateMetrics().
422 // The second drawing step is done in WorkArea::redraw() if needed.
424 // Case when no explicit update is requested.
426 // no need to redraw anything.
427 d->update_strategy_ = NoScreenUpdate;
431 if (flags == Update::Decoration) {
432 d->update_strategy_ = DecorationUpdate;
433 buffer_.changed(false);
437 if (flags == Update::FitCursor
438 || flags == (Update::Decoration | Update::FitCursor)) {
439 // tell the frontend to update the screen if needed.
444 if (flags & Update::Decoration) {
445 d->update_strategy_ = DecorationUpdate;
446 buffer_.changed(false);
449 // no screen update is needed.
450 d->update_strategy_ = NoScreenUpdate;
454 bool const full_metrics = flags & Update::Force || !singleParUpdate();
457 // We have to update the full screen metrics.
460 if (!(flags & Update::FitCursor)) {
461 // Nothing to do anymore. Trigger a redraw and return
462 buffer_.changed(false);
466 // updateMetrics() does not update paragraph position
467 // This is done at draw() time. So we need a redraw!
468 buffer_.changed(false);
471 // The cursor is off screen so ensure it is visible.
476 updateHoveredInset();
480 void BufferView::updateScrollbar()
482 if (height_ == 0 && width_ == 0)
485 // We prefer fixed size line scrolling.
486 d->scrollbarParameters_.single_step = defaultRowHeight();
487 // We prefer full screen page scrolling.
488 d->scrollbarParameters_.page_step = height_;
490 Text & t = buffer_.text();
491 TextMetrics & tm = d->text_metrics_[&t];
493 LYXERR(Debug::GUI, " Updating scrollbar: height: "
494 << t.paragraphs().size()
495 << " curr par: " << d->cursor_.bottom().pit()
496 << " default height " << defaultRowHeight());
498 size_t const parsize = t.paragraphs().size();
499 if (d->par_height_.size() != parsize) {
500 d->par_height_.clear();
501 // FIXME: We assume a default paragraph height of 2 rows. This
502 // should probably be pondered with the screen width.
503 d->par_height_.resize(parsize, defaultRowHeight() * 2);
506 // Look at paragraph heights on-screen
507 pair<pit_type, ParagraphMetrics const *> first = tm.first();
508 pair<pit_type, ParagraphMetrics const *> last = tm.last();
509 for (pit_type pit = first.first; pit <= last.first; ++pit) {
510 d->par_height_[pit] = tm.parMetrics(pit).height();
511 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
512 << d->par_height_[pit]);
515 int top_pos = first.second->position() - first.second->ascent();
516 int bottom_pos = last.second->position() + last.second->descent();
517 bool first_visible = first.first == 0 && top_pos >= 0;
518 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
519 if (first_visible && last_visible) {
520 d->scrollbarParameters_.min = 0;
521 d->scrollbarParameters_.max = 0;
525 d->scrollbarParameters_.min = top_pos;
526 for (size_t i = 0; i != size_t(first.first); ++i)
527 d->scrollbarParameters_.min -= d->par_height_[i];
528 d->scrollbarParameters_.max = bottom_pos;
529 for (size_t i = last.first + 1; i != parsize; ++i)
530 d->scrollbarParameters_.max += d->par_height_[i];
532 d->scrollbarParameters_.position = 0;
533 // The reference is the top position so we remove one page.
534 if (lyxrc.scroll_below_document)
535 d->scrollbarParameters_.max -= minVisiblePart();
537 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
541 ScrollbarParameters const & BufferView::scrollbarParameters() const
543 return d->scrollbarParameters_;
547 docstring BufferView::toolTip(int x, int y) const
549 // Get inset under mouse, if there is one.
550 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
552 // No inset, no tooltip...
554 return covering_inset->toolTip(*this, x, y);
558 docstring BufferView::contextMenu(int x, int y) const
560 //If there is a selection, return the containing inset menu
561 if (d->cursor_.selection())
562 return d->cursor_.inset().contextMenu(*this, x, y);
564 // Get inset under mouse, if there is one.
565 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
567 return covering_inset->contextMenu(*this, x, y);
569 return buffer_.inset().contextMenu(*this, x, y);
573 void BufferView::scrollDocView(int value, bool update)
575 int const offset = value - d->scrollbarParameters_.position;
577 // No scrolling at all? No need to redraw anything
581 // If the offset is less than 2 screen height, prefer to scroll instead.
582 if (abs(offset) <= 2 * height_) {
583 d->anchor_ypos_ -= offset;
584 buffer_.changed(true);
585 updateHoveredInset();
589 // cut off at the top
590 if (value <= d->scrollbarParameters_.min) {
591 DocIterator dit = doc_iterator_begin(&buffer_);
592 showCursor(dit, false, update);
593 LYXERR(Debug::SCROLLING, "scroll to top");
597 // cut off at the bottom
598 if (value >= d->scrollbarParameters_.max) {
599 DocIterator dit = doc_iterator_end(&buffer_);
601 showCursor(dit, false, update);
602 LYXERR(Debug::SCROLLING, "scroll to bottom");
606 // find paragraph at target position
607 int par_pos = d->scrollbarParameters_.min;
609 for (; i != int(d->par_height_.size()); ++i) {
610 par_pos += d->par_height_[i];
611 if (par_pos >= value)
615 if (par_pos < value) {
616 // It seems we didn't find the correct pit so stay on the safe side and
618 LYXERR0("scrolling position not found!");
619 scrollDocView(d->scrollbarParameters_.max, update);
623 DocIterator dit = doc_iterator_begin(&buffer_);
625 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
626 showCursor(dit, false, update);
630 // FIXME: this method is not working well.
631 void BufferView::setCursorFromScrollbar()
633 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
635 int const height = 2 * defaultRowHeight();
636 int const first = height;
637 int const last = height_ - height;
639 Cursor const & oldcur = d->cursor_;
641 switch (cursorStatus(oldcur)) {
649 int const y = getPos(oldcur).y_;
650 newy = min(last, max(y, first));
654 // We reset the cursor because cursorStatus() does not
655 // work when the cursor is within mathed.
658 tm.setCursorFromCoordinates(cur, 0, newy);
660 // update the bufferview cursor and notify insets
661 // FIXME: Care about the d->cursor_ flags to redraw if needed
662 Cursor old = d->cursor_;
664 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
666 d->cursor_.fixIfBroken();
670 Change const BufferView::getCurrentChange() const
672 if (!d->cursor_.selection())
673 return Change(Change::UNCHANGED);
675 DocIterator dit = d->cursor_.selectionBegin();
676 return dit.paragraph().lookupChange(dit.pos());
680 // this could be used elsewhere as well?
681 // FIXME: This does not work within mathed!
682 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
684 Point const p = getPos(dit);
687 if (p.y_ > workHeight())
693 void BufferView::bookmarkEditPosition()
695 // Don't eat cpu time for each keystroke
696 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
699 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
703 void BufferView::saveBookmark(unsigned int idx)
705 // tentatively save bookmark, id and pos will be used to
706 // acturately locate a bookmark in a 'live' lyx session.
707 // pit and pos will be updated with bottom level pit/pos
709 if (!buffer_.isInternal()) {
710 theSession().bookmarks().save(
712 d->cursor_.bottom().pit(),
713 d->cursor_.bottom().pos(),
714 d->cursor_.paragraph().id(),
719 // emit message signal.
720 message(_("Save bookmark"));
725 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
726 int top_id, pos_type top_pos)
728 bool success = false;
731 d->cursor_.clearSelection();
733 // if a valid par_id is given, try it first
734 // This is the case for a 'live' bookmark when unique paragraph ID
735 // is used to track bookmarks.
737 dit = buffer_.getParFromID(top_id);
739 dit.pos() = min(dit.paragraph().size(), top_pos);
740 // Some slices of the iterator may not be
741 // reachable (e.g. closed collapsable inset)
742 // so the dociterator may need to be
743 // shortened. Otherwise, setCursor may crash
744 // lyx when the cursor can not be set to these
746 size_t const n = dit.depth();
747 for (size_t i = 0; i < n; ++i)
748 if (!dit[i].inset().editable()) {
756 // if top_id == 0, or searching through top_id failed
757 // This is the case for a 'restored' bookmark when only bottom
758 // (document level) pit was saved. Because of this, bookmark
759 // restoration is inaccurate. If a bookmark was within an inset,
760 // it will be restored to the left of the outmost inset that contains
762 if (bottom_pit < int(buffer_.paragraphs().size())) {
763 dit = doc_iterator_begin(&buffer_);
765 dit.pit() = bottom_pit;
766 dit.pos() = min(bottom_pos, dit.paragraph().size());
771 // Note: only bottom (document) level pit is set.
773 // set the current font.
774 d->cursor_.setCurrentFont();
775 // To center the screen on this new position we need the
776 // paragraph position which is computed at draw() time.
777 // So we need a redraw!
778 buffer_.changed(false);
787 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
789 if (lyxrc.rtl_support) {
790 if (d->cursor_.real_current_font.isRightToLeft()) {
791 if (d->intl_.keymap == Intl::PRIMARY)
792 d->intl_.keyMapSec();
794 if (d->intl_.keymap == Intl::SECONDARY)
795 d->intl_.keyMapPrim();
799 d->intl_.getTransManager().translateAndInsert(c, t, cur);
803 int BufferView::workWidth() const
809 void BufferView::recenter()
811 showCursor(d->cursor_, true, true);
815 void BufferView::showCursor()
817 showCursor(d->cursor_, false, true);
821 void BufferView::showCursor(DocIterator const & dit,
822 bool recenter, bool update)
824 if (scrollToCursor(dit, recenter) && update) {
825 buffer_.changed(true);
826 updateHoveredInset();
831 void BufferView::scrollToCursor()
833 if (scrollToCursor(d->cursor_, false)) {
834 buffer_.changed(true);
835 updateHoveredInset();
840 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
842 // We are not properly started yet, delay until resizing is
847 LYXERR(Debug::SCROLLING, "recentering!");
849 CursorSlice const & bot = dit.bottom();
850 TextMetrics & tm = d->text_metrics_[bot.text()];
852 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
853 int bot_pit = bot.pit();
854 if (bot_pit > max_pit) {
855 // FIXME: Why does this happen?
856 LYXERR0("bottom pit is greater that max pit: "
857 << bot_pit << " > " << max_pit);
861 if (bot_pit == tm.first().first - 1)
862 tm.newParMetricsUp();
863 else if (bot_pit == tm.last().first + 1)
864 tm.newParMetricsDown();
866 if (tm.contains(bot_pit)) {
867 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
868 LASSERT(!pm.rows().empty(), /**/);
869 // FIXME: smooth scrolling doesn't work in mathed.
870 CursorSlice const & cs = dit.innerTextSlice();
871 int offset = coordOffset(dit).y_;
872 int ypos = pm.position() + offset;
873 Dimension const & row_dim =
874 pm.getRow(cs.pos(), dit.boundary()).dimension();
877 scrolled = scroll(ypos - height_/2);
879 // If the top part of the row falls of the screen, we scroll
880 // up to align the top of the row with the top of the screen.
881 else if (ypos - row_dim.ascent() < 0)
882 scrolled = scrollUp(-ypos + row_dim.ascent());
884 // If the bottom of the row falls of the screen, we scroll down.
885 // However, we have to be careful not to scroll that much that
886 // the top falls of the screen.
887 else if (ypos + row_dim.descent() > height_) {
888 int ynew = height_ - row_dim.descent();
889 if (ynew < row_dim.ascent())
890 ynew = row_dim.ascent();
891 int const scroll = ypos - ynew;
892 scrolled = scrollDown(scroll);
895 // else, nothing to do, the cursor is already visible so we just return.
896 return scrolled != 0;
899 // fix inline completion position
900 if (d->inlineCompletionPos_.fixIfBroken())
901 d->inlineCompletionPos_ = DocIterator();
903 tm.redoParagraph(bot_pit);
904 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
905 int offset = coordOffset(dit).y_;
907 d->anchor_pit_ = bot_pit;
908 CursorSlice const & cs = dit.innerTextSlice();
909 Dimension const & row_dim =
910 pm.getRow(cs.pos(), dit.boundary()).dimension();
913 d->anchor_ypos_ = height_/2;
914 else if (d->anchor_pit_ == 0)
915 d->anchor_ypos_ = offset + pm.ascent();
916 else if (d->anchor_pit_ == max_pit)
917 d->anchor_ypos_ = height_ - offset - row_dim.descent();
918 else if (offset > height_)
919 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
921 d->anchor_ypos_ = defaultRowHeight() * 2;
927 void BufferView::updateDocumentClass(DocumentClass const * const olddc)
929 message(_("Converting document to new document class..."));
931 StableDocIterator backcur(d->cursor_);
932 ErrorList & el = buffer_.errorList("Class Switch");
933 cap::switchBetweenClasses(
934 olddc, buffer_.params().documentClassPtr(),
935 static_cast<InsetText &>(buffer_.inset()), el);
937 setCursor(backcur.asDocIterator(&buffer_));
939 buffer_.errors("Class Switch");
942 /** Return the change status at cursor position, taking in account the
943 * status at each level of the document iterator (a table in a deleted
944 * footnote is deleted).
945 * When \param outer is true, the top slice is not looked at.
947 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
949 size_t const depth = dit.depth() - (outer ? 1 : 0);
951 for (size_t i = 0 ; i < depth ; ++i) {
952 CursorSlice const & slice = dit[i];
953 if (!slice.inset().inMathed()
954 && slice.pos() < slice.paragraph().size()) {
955 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
956 if (ch != Change::UNCHANGED)
960 return Change::UNCHANGED;
964 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
966 FuncCode const act = cmd.action();
968 // Can we use a readonly buffer?
969 if (buffer_.isReadonly()
970 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
971 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
972 flag.message(from_utf8(N_("Document is read-only")));
973 flag.setEnabled(false);
977 // Are we in a DELETED change-tracking region?
978 if (lookupChangeType(d->cursor_, true) == Change::DELETED
979 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
980 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
981 flag.message(from_utf8(N_("This portion of the document is deleted.")));
982 flag.setEnabled(false);
986 Cursor & cur = d->cursor_;
988 if (cur.getStatus(cmd, flag))
993 // FIXME: This is a bit problematic because we don't check if this is
994 // a document BufferView or not for these LFUNs. We probably have to
995 // dispatch both to currentBufferView() and, if that fails,
996 // to documentBufferView(); same as we do now for current Buffer and
997 // document Buffer. Ideally those LFUN should go to Buffer as they
998 // operate on the full Buffer and the cursor is only needed either for
999 // an Undo record or to restore a cursor position. But we don't know
1000 // how to do that inside Buffer of course.
1001 case LFUN_BUFFER_PARAMS_APPLY:
1002 case LFUN_LAYOUT_MODULES_CLEAR:
1003 case LFUN_LAYOUT_MODULE_ADD:
1004 case LFUN_LAYOUT_RELOAD:
1005 case LFUN_TEXTCLASS_APPLY:
1006 case LFUN_TEXTCLASS_LOAD:
1007 flag.setEnabled(!buffer_.isReadonly());
1011 // We do not use the LyXAction flag for readonly because Undo sets the
1012 // buffer clean/dirty status by itself.
1013 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1016 // We do not use the LyXAction flag for readonly because Redo sets the
1017 // buffer clean/dirty status by itself.
1018 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1020 case LFUN_FILE_INSERT:
1021 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1022 case LFUN_FILE_INSERT_PLAINTEXT:
1023 case LFUN_BOOKMARK_SAVE:
1024 // FIXME: Actually, these LFUNS should be moved to Text
1025 flag.setEnabled(cur.inTexted());
1028 case LFUN_FONT_STATE:
1029 case LFUN_LABEL_INSERT:
1030 case LFUN_INFO_INSERT:
1031 case LFUN_PARAGRAPH_GOTO:
1032 case LFUN_NOTE_NEXT:
1033 case LFUN_REFERENCE_NEXT:
1034 case LFUN_WORD_FIND:
1035 case LFUN_WORD_FIND_FORWARD:
1036 case LFUN_WORD_FIND_BACKWARD:
1037 case LFUN_WORD_FINDADV:
1038 case LFUN_WORD_REPLACE:
1041 case LFUN_MARK_TOGGLE:
1042 case LFUN_SCREEN_RECENTER:
1043 case LFUN_SCREEN_SHOW_CURSOR:
1044 case LFUN_BIBTEX_DATABASE_ADD:
1045 case LFUN_BIBTEX_DATABASE_DEL:
1046 case LFUN_STATISTICS:
1047 case LFUN_BRANCH_ADD_INSERT:
1048 case LFUN_KEYMAP_OFF:
1049 case LFUN_KEYMAP_PRIMARY:
1050 case LFUN_KEYMAP_SECONDARY:
1051 case LFUN_KEYMAP_TOGGLE:
1052 flag.setEnabled(true);
1055 case LFUN_LABEL_GOTO: {
1056 flag.setEnabled(!cmd.argument().empty()
1057 || getInsetByCode<InsetRef>(cur, REF_CODE));
1061 case LFUN_CHANGES_TRACK:
1062 flag.setEnabled(true);
1063 flag.setOnOff(buffer_.params().trackChanges);
1066 case LFUN_CHANGES_OUTPUT:
1067 flag.setEnabled(true);
1068 flag.setOnOff(buffer_.params().outputChanges);
1071 case LFUN_CHANGES_MERGE:
1072 case LFUN_CHANGE_NEXT:
1073 case LFUN_CHANGE_PREVIOUS:
1074 case LFUN_ALL_CHANGES_ACCEPT:
1075 case LFUN_ALL_CHANGES_REJECT:
1076 // TODO: context-sensitive enabling of LFUNs
1077 // In principle, these command should only be enabled if there
1078 // is a change in the document. However, without proper
1079 // optimizations, this will inevitably result in poor performance.
1080 flag.setEnabled(true);
1083 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1084 flag.setOnOff(buffer_.params().compressed);
1088 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
1089 flag.setOnOff(buffer_.params().output_sync);
1093 case LFUN_SCREEN_UP:
1094 case LFUN_SCREEN_DOWN:
1096 case LFUN_SCREEN_UP_SELECT:
1097 case LFUN_SCREEN_DOWN_SELECT:
1098 case LFUN_INSET_FORALL:
1099 flag.setEnabled(true);
1102 case LFUN_LAYOUT_TABULAR:
1103 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1107 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1110 case LFUN_LAYOUT_PARAGRAPH:
1111 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1114 case LFUN_DIALOG_SHOW_NEW_INSET:
1115 // FIXME: this is wrong, but I do not understand the
1117 if (cur.inset().lyxCode() == CAPTION_CODE)
1118 return cur.inset().getStatus(cur, cmd, flag);
1119 // FIXME we should consider passthru paragraphs too.
1120 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1123 case LFUN_CITATION_INSERT: {
1124 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1125 // FIXME: This could turn in a recursive hell.
1126 // Shouldn't we use Buffer::getStatus() instead?
1127 flag.setEnabled(lyx::getStatus(fr).enabled());
1130 case LFUN_INSET_APPLY: {
1131 string const name = cmd.getArg(0);
1132 Inset * inset = editedInset(name);
1134 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1135 if (!inset->getStatus(cur, fr, flag)) {
1136 // Every inset is supposed to handle this
1137 LASSERT(false, break);
1140 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1141 flag = lyx::getStatus(fr);
1154 Inset * BufferView::editedInset(string const & name) const
1156 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1157 return it == d->edited_insets_.end() ? 0 : it->second;
1161 void BufferView::editInset(string const & name, Inset * inset)
1163 d->edited_insets_[name] = inset;
1167 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1169 //lyxerr << [ cmd = " << cmd << "]" << endl;
1171 // Make sure that the cached BufferView is correct.
1172 LYXERR(Debug::ACTION, " action[" << cmd.action() << ']'
1173 << " arg[" << to_utf8(cmd.argument()) << ']'
1174 << " x[" << cmd.x() << ']'
1175 << " y[" << cmd.y() << ']'
1176 << " button[" << cmd.button() << ']');
1178 string const argument = to_utf8(cmd.argument());
1179 Cursor & cur = d->cursor_;
1181 // Don't dispatch function that does not apply to internal buffers.
1182 if (buffer_.isInternal()
1183 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1186 // We'll set this back to false if need be.
1187 bool dispatched = true;
1188 buffer_.undo().beginUndoGroup();
1190 FuncCode const act = cmd.action();
1193 case LFUN_BUFFER_PARAMS_APPLY: {
1194 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1195 cur.recordUndoFullDocument();
1196 istringstream ss(to_utf8(cmd.argument()));
1199 int const unknown_tokens = buffer_.readHeader(lex);
1200 if (unknown_tokens != 0) {
1201 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1202 << unknown_tokens << " unknown token"
1203 << (unknown_tokens == 1 ? "" : "s"));
1205 updateDocumentClass(oldClass);
1207 // We are most certainly here because of a change in the document
1208 // It is then better to make sure that all dialogs are in sync with
1209 // current document settings.
1210 dr.screenUpdate(Update::Force | Update::FitCursor);
1211 dr.forceBufferUpdate();
1215 case LFUN_LAYOUT_MODULES_CLEAR: {
1216 DocumentClass const * const oldClass =
1217 buffer_.params().documentClassPtr();
1218 cur.recordUndoFullDocument();
1219 buffer_.params().clearLayoutModules();
1220 buffer_.params().makeDocumentClass();
1221 updateDocumentClass(oldClass);
1222 dr.screenUpdate(Update::Force);
1223 dr.forceBufferUpdate();
1227 case LFUN_LAYOUT_MODULE_ADD: {
1228 BufferParams const & params = buffer_.params();
1229 if (!params.moduleCanBeAdded(argument)) {
1230 LYXERR0("Module `" << argument <<
1231 "' cannot be added due to failed requirements or "
1232 "conflicts with installed modules.");
1235 DocumentClass const * const oldClass = params.documentClassPtr();
1236 cur.recordUndoFullDocument();
1237 buffer_.params().addLayoutModule(argument);
1238 buffer_.params().makeDocumentClass();
1239 updateDocumentClass(oldClass);
1240 dr.screenUpdate(Update::Force);
1241 dr.forceBufferUpdate();
1245 case LFUN_TEXTCLASS_APPLY: {
1246 // since this shortcircuits, the second call is made only if
1248 bool const success =
1249 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1250 LayoutFileList::get().load(argument, buffer_.filePath());
1252 docstring s = bformat(_("The document class `%1$s' "
1253 "could not be loaded."), from_utf8(argument));
1254 frontend::Alert::error(_("Could not load class"), s);
1258 LayoutFile const * old_layout = buffer_.params().baseClass();
1259 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1261 if (old_layout == new_layout)
1265 // Save the old, possibly modular, layout for use in conversion.
1266 DocumentClass const * const oldDocClass =
1267 buffer_.params().documentClassPtr();
1268 cur.recordUndoFullDocument();
1269 buffer_.params().setBaseClass(argument);
1270 buffer_.params().makeDocumentClass();
1271 updateDocumentClass(oldDocClass);
1272 dr.screenUpdate(Update::Force);
1273 dr.forceBufferUpdate();
1277 case LFUN_TEXTCLASS_LOAD: {
1278 // since this shortcircuits, the second call is made only if
1280 bool const success =
1281 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1282 LayoutFileList::get().load(argument, buffer_.filePath());
1284 docstring s = bformat(_("The document class `%1$s' "
1285 "could not be loaded."), from_utf8(argument));
1286 frontend::Alert::error(_("Could not load class"), s);
1291 case LFUN_LAYOUT_RELOAD: {
1292 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1293 LayoutFileIndex bc = buffer_.params().baseClassID();
1294 LayoutFileList::get().reset(bc);
1295 buffer_.params().setBaseClass(bc);
1296 buffer_.params().makeDocumentClass();
1297 updateDocumentClass(oldClass);
1298 dr.screenUpdate(Update::Force);
1299 dr.forceBufferUpdate();
1304 dr.setMessage(_("Undo"));
1305 cur.clearSelection();
1306 if (!cur.textUndo())
1307 dr.setMessage(_("No further undo information"));
1309 dr.screenUpdate(Update::Force | Update::FitCursor);
1310 dr.forceBufferUpdate();
1314 dr.setMessage(_("Redo"));
1315 cur.clearSelection();
1316 if (!cur.textRedo())
1317 dr.setMessage(_("No further redo information"));
1319 dr.screenUpdate(Update::Force | Update::FitCursor);
1320 dr.forceBufferUpdate();
1323 case LFUN_FONT_STATE:
1324 dr.setMessage(cur.currentState());
1327 case LFUN_BOOKMARK_SAVE:
1328 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1331 case LFUN_LABEL_GOTO: {
1332 docstring label = cmd.argument();
1333 if (label.empty()) {
1335 getInsetByCode<InsetRef>(cur, REF_CODE);
1337 label = inset->getParam("reference");
1338 // persistent=false: use temp_bookmark
1342 if (!label.empty()) {
1344 // at the moment, this is redundant, since gotoLabel will
1345 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1347 dr.screenUpdate(Update::Force | Update::FitCursor);
1352 case LFUN_PARAGRAPH_GOTO: {
1353 int const id = convert<int>(cmd.getArg(0));
1354 int const pos = convert<int>(cmd.getArg(1));
1356 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1357 b = theBufferList().next(b)) {
1359 DocIterator dit = b->getParFromID(id);
1361 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1365 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1366 << " found in buffer `"
1367 << b->absFileName() << "'.");
1369 if (b == &buffer_) {
1373 dr.screenUpdate(Update::Force | Update::FitCursor);
1375 // Switch to other buffer view and resend cmd
1376 lyx::dispatch(FuncRequest(
1377 LFUN_BUFFER_SWITCH, b->absFileName()));
1385 case LFUN_NOTE_NEXT:
1386 gotoInset(this, NOTE_CODE, false);
1389 case LFUN_REFERENCE_NEXT: {
1390 vector<InsetCode> tmp;
1391 tmp.push_back(LABEL_CODE);
1392 tmp.push_back(REF_CODE);
1393 gotoInset(this, tmp, true);
1397 case LFUN_CHANGES_TRACK:
1398 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1401 case LFUN_CHANGES_OUTPUT:
1402 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1403 if (buffer_.params().outputChanges) {
1404 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1405 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1406 LaTeXFeatures::isAvailable("xcolor");
1408 if (!dvipost && !xcolorulem) {
1409 Alert::warning(_("Changes not shown in LaTeX output"),
1410 _("Changes will not be highlighted in LaTeX output, "
1411 "because neither dvipost nor xcolor/ulem are installed.\n"
1412 "Please install these packages or redefine "
1413 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1414 } else if (!xcolorulem) {
1415 Alert::warning(_("Changes not shown in LaTeX output"),
1416 _("Changes will not be highlighted in LaTeX output "
1417 "when using pdflatex, because xcolor and ulem are not installed.\n"
1418 "Please install both packages or redefine "
1419 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1424 case LFUN_CHANGE_NEXT:
1425 findNextChange(this);
1426 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1427 dr.screenUpdate(Update::Force | Update::FitCursor);
1430 case LFUN_CHANGE_PREVIOUS:
1431 findPreviousChange(this);
1432 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1433 dr.screenUpdate(Update::Force | Update::FitCursor);
1436 case LFUN_CHANGES_MERGE:
1437 if (findNextChange(this) || findPreviousChange(this)) {
1438 dr.screenUpdate(Update::Force | Update::FitCursor);
1439 dr.forceBufferUpdate();
1440 showDialog("changes");
1444 case LFUN_ALL_CHANGES_ACCEPT:
1445 // select complete document
1447 cur.selHandle(true);
1448 buffer_.text().cursorBottom(cur);
1449 // accept everything in a single step to support atomic undo
1450 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1451 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1452 dr.screenUpdate(Update::Force | Update::FitCursor);
1453 dr.forceBufferUpdate();
1456 case LFUN_ALL_CHANGES_REJECT:
1457 // select complete document
1459 cur.selHandle(true);
1460 buffer_.text().cursorBottom(cur);
1461 // reject everything in a single step to support atomic undo
1462 // Note: reject does not work recursively; the user may have to repeat the operation
1463 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1464 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1465 dr.screenUpdate(Update::Force | Update::FitCursor);
1466 dr.forceBufferUpdate();
1469 case LFUN_WORD_FIND_FORWARD:
1470 case LFUN_WORD_FIND_BACKWARD: {
1471 static docstring last_search;
1472 docstring searched_string;
1474 if (!cmd.argument().empty()) {
1475 last_search = cmd.argument();
1476 searched_string = cmd.argument();
1478 searched_string = last_search;
1481 if (searched_string.empty())
1484 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1485 docstring const data =
1486 find2string(searched_string, true, false, fw);
1487 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1489 dr.screenUpdate(Update::Force | Update::FitCursor);
1493 case LFUN_WORD_FIND: {
1494 FuncRequest req = cmd;
1495 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1496 req = d->search_request_cache_;
1497 if (req.argument().empty()) {
1498 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1501 if (lyxfind(this, req))
1502 dr.screenUpdate(Update::Force | Update::FitCursor);
1504 message(_("String not found!"));
1505 d->search_request_cache_ = req;
1509 case LFUN_WORD_REPLACE: {
1510 bool has_deleted = false;
1511 if (cur.selection()) {
1512 DocIterator beg = cur.selectionBegin();
1513 DocIterator end = cur.selectionEnd();
1514 if (beg.pit() == end.pit()) {
1515 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1516 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1523 if (lyxreplace(this, cmd, has_deleted)) {
1524 dr.forceBufferUpdate();
1525 dr.screenUpdate(Update::Force | Update::FitCursor);
1530 case LFUN_WORD_FINDADV: {
1531 FindAndReplaceOptions opt;
1532 istringstream iss(to_utf8(cmd.argument()));
1534 if (findAdv(this, opt))
1535 dr.screenUpdate(Update::Force | Update::FitCursor);
1540 cur.clearSelection();
1541 dr.setMessage(from_utf8(N_("Mark off")));
1545 cur.clearSelection();
1547 dr.setMessage(from_utf8(N_("Mark on")));
1550 case LFUN_MARK_TOGGLE:
1551 cur.setSelection(false);
1554 dr.setMessage(from_utf8(N_("Mark removed")));
1557 dr.setMessage(from_utf8(N_("Mark set")));
1562 case LFUN_SCREEN_SHOW_CURSOR:
1566 case LFUN_SCREEN_RECENTER:
1570 case LFUN_BIBTEX_DATABASE_ADD: {
1571 Cursor tmpcur = cur;
1572 findInset(tmpcur, BIBTEX_CODE, false);
1573 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1576 if (inset->addDatabase(cmd.argument())) {
1577 buffer_.invalidateBibfileCache();
1578 dr.forceBufferUpdate();
1584 case LFUN_BIBTEX_DATABASE_DEL: {
1585 Cursor tmpcur = cur;
1586 findInset(tmpcur, BIBTEX_CODE, false);
1587 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1590 if (inset->delDatabase(cmd.argument())) {
1591 buffer_.invalidateBibfileCache();
1592 dr.forceBufferUpdate();
1598 case LFUN_STATISTICS: {
1599 DocIterator from, to;
1600 if (cur.selection()) {
1601 from = cur.selectionBegin();
1602 to = cur.selectionEnd();
1604 from = doc_iterator_begin(&buffer_);
1605 to = doc_iterator_end(&buffer_);
1607 int const words = countWords(from, to);
1608 int const chars = countChars(from, to, false);
1609 int const chars_blanks = countChars(from, to, true);
1611 if (cur.selection())
1612 message = _("Statistics for the selection:");
1614 message = _("Statistics for the document:");
1617 message += bformat(_("%1$d words"), words);
1619 message += _("One word");
1621 if (chars_blanks != 1)
1622 message += bformat(_("%1$d characters (including blanks)"),
1625 message += _("One character (including blanks)");
1628 message += bformat(_("%1$d characters (excluding blanks)"),
1631 message += _("One character (excluding blanks)");
1633 Alert::information(_("Statistics"), message);
1637 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1638 // turn compression on/off
1639 buffer_.params().compressed = !buffer_.params().compressed;
1642 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
1643 buffer_.params().output_sync = !buffer_.params().output_sync;
1646 case LFUN_SCREEN_UP:
1647 case LFUN_SCREEN_DOWN: {
1648 Point p = getPos(cur);
1649 // This code has been commented out to enable to scroll down a
1650 // document, even if there are large insets in it (see bug #5465).
1651 /*if (p.y_ < 0 || p.y_ > height_) {
1652 // The cursor is off-screen so recenter before proceeding.
1656 int const scrolled = scroll(act == LFUN_SCREEN_UP
1657 ? -height_ : height_);
1658 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1660 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1661 p = Point(width_, height_);
1663 bool const in_texted = cur.inTexted();
1665 buffer_.changed(true);
1666 updateHoveredInset();
1668 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1669 true, act == LFUN_SCREEN_UP);
1670 //FIXME: what to do with cur.x_target()?
1671 bool update = in_texted && cur.bv().checkDepm(cur, old);
1674 dr.screenUpdate(Update::Force | Update::FitCursor);
1675 dr.forceBufferUpdate();
1682 dr.forceBufferUpdate();
1685 case LFUN_SCREEN_UP_SELECT: {
1686 cur.selHandle(true);
1687 if (isTopScreen()) {
1688 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1692 int y = getPos(cur).y_;
1693 int const ymin = y - height_ + defaultRowHeight();
1694 while (y > ymin && cur.up())
1698 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1702 case LFUN_SCREEN_DOWN_SELECT: {
1703 cur.selHandle(true);
1704 if (isBottomScreen()) {
1705 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1709 int y = getPos(cur).y_;
1710 int const ymax = y + height_ - defaultRowHeight();
1711 while (y < ymax && cur.down())
1715 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1720 // This would be in Buffer class if only Cursor did not
1721 // require a bufferview
1722 case LFUN_INSET_FORALL: {
1723 docstring const name = from_utf8(cmd.getArg(0));
1724 string const commandstr = cmd.getLongArg(1);
1725 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1727 // an arbitrary number to limit number of iterations
1728 const int max_iter = 10000;
1730 Cursor & cur = d->cursor_;
1731 Cursor const savecur = cur;
1733 if (!cur.nextInset())
1735 cur.beginUndoGroup();
1736 while(cur && iterations < max_iter) {
1737 Inset * ins = cur.nextInset();
1740 docstring insname = ins->name();
1741 while (!insname.empty()) {
1742 if (insname == name || name == from_utf8("*")) {
1744 lyx::dispatch(fr, dr);
1748 size_t const i = insname.rfind(':');
1749 if (i == string::npos)
1751 insname = insname.substr(0, i);
1758 dr.screenUpdate(Update::Force);
1759 dr.forceBufferUpdate();
1761 if (iterations >= max_iter) {
1763 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1765 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1770 case LFUN_BRANCH_ADD_INSERT: {
1771 docstring branch_name = from_utf8(cmd.getArg(0));
1772 if (branch_name.empty())
1773 if (!Alert::askForText(branch_name, _("Branch name")) ||
1774 branch_name.empty())
1777 DispatchResult drtmp;
1778 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1779 if (drtmp.error()) {
1780 Alert::warning(_("Branch already exists"), drtmp.message());
1783 BranchList & branch_list = buffer_.params().branchlist();
1784 vector<docstring> const branches =
1785 getVectorFromString(branch_name, branch_list.separator());
1786 for (vector<docstring>::const_iterator it = branches.begin();
1787 it != branches.end(); ++it) {
1789 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1794 case LFUN_KEYMAP_OFF:
1795 getIntl().keyMapOn(false);
1798 case LFUN_KEYMAP_PRIMARY:
1799 getIntl().keyMapPrim();
1802 case LFUN_KEYMAP_SECONDARY:
1803 getIntl().keyMapSec();
1806 case LFUN_KEYMAP_TOGGLE:
1807 getIntl().toggleKeyMap();
1810 case LFUN_DIALOG_SHOW_NEW_INSET: {
1811 string const name = cmd.getArg(0);
1812 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1813 if (decodeInsetParam(name, data, buffer_))
1814 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1816 lyxerr << "Inset type '" << name <<
1817 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1821 case LFUN_CITATION_INSERT: {
1822 if (argument.empty()) {
1823 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1826 // we can have one optional argument, delimited by '|'
1827 // citation-insert <key>|<text_before>
1828 // this should be enhanced to also support text_after
1829 // and citation style
1830 string arg = argument;
1832 if (contains(argument, "|")) {
1833 arg = token(argument, '|', 0);
1834 opt1 = token(argument, '|', 1);
1836 InsetCommandParams icp(CITE_CODE);
1837 icp["key"] = from_utf8(arg);
1839 icp["before"] = from_utf8(opt1);
1840 string icstr = InsetCommand::params2string("citation", icp);
1841 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1846 case LFUN_INSET_APPLY: {
1847 string const name = cmd.getArg(0);
1848 Inset * inset = editedInset(name);
1850 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1854 // put cursor in front of inset.
1855 if (!setCursorFromInset(inset)) {
1856 LASSERT(false, break);
1859 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1860 inset->dispatch(cur, fr);
1861 dr.screenUpdate(cur.result().screenUpdate());
1862 if (cur.result().needBufferUpdate())
1863 dr.forceBufferUpdate();
1872 buffer_.undo().endUndoGroup();
1873 dr.dispatched(dispatched);
1878 docstring const BufferView::requestSelection()
1880 Cursor & cur = d->cursor_;
1882 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1883 if (!cur.selection()) {
1884 d->xsel_cache_.set = false;
1888 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1889 if (!d->xsel_cache_.set ||
1890 cur.top() != d->xsel_cache_.cursor ||
1891 cur.realAnchor().top() != d->xsel_cache_.anchor)
1893 d->xsel_cache_.cursor = cur.top();
1894 d->xsel_cache_.anchor = cur.realAnchor().top();
1895 d->xsel_cache_.set = cur.selection();
1896 return cur.selectionAsString(false);
1902 void BufferView::clearSelection()
1904 d->cursor_.clearSelection();
1905 // Clear the selection buffer. Otherwise a subsequent
1906 // middle-mouse-button paste would use the selection buffer,
1907 // not the more current external selection.
1908 cap::clearSelection();
1909 d->xsel_cache_.set = false;
1910 // The buffer did not really change, but this causes the
1911 // redraw we need because we cleared the selection above.
1912 buffer_.changed(false);
1916 void BufferView::resize(int width, int height)
1918 // Update from work area
1922 // Clear the paragraph height cache.
1923 d->par_height_.clear();
1924 // Redo the metrics.
1929 Inset const * BufferView::getCoveringInset(Text const & text,
1932 TextMetrics & tm = d->text_metrics_[&text];
1933 Inset * inset = tm.checkInsetHit(x, y);
1937 if (!inset->descendable(*this))
1938 // No need to go further down if the inset is not
1942 size_t cell_number = inset->nargs();
1943 // Check all the inner cell.
1944 for (size_t i = 0; i != cell_number; ++i) {
1945 Text const * inner_text = inset->getText(i);
1948 Inset const * inset_deeper =
1949 getCoveringInset(*inner_text, x, y);
1951 return inset_deeper;
1959 void BufferView::updateHoveredInset() const
1961 // Get inset under mouse, if there is one.
1962 Inset const * covering_inset = getCoveringInset(buffer_.text(),
1963 d->mouse_position_cache_.x_, d->mouse_position_cache_.y_);
1964 if (covering_inset == d->last_inset_)
1965 // Same inset, no need to do anything...
1968 bool need_redraw = false;
1969 if (d->last_inset_) {
1970 // Remove the hint on the last hovered inset (if any).
1971 need_redraw |= d->last_inset_->setMouseHover(this, false);
1975 // const_cast because of setMouseHover().
1976 Inset * inset = const_cast<Inset *>(covering_inset);
1977 if (inset && inset->setMouseHover(this, true)) {
1979 // Only the insets that accept the hover state, do
1980 // clear the last_inset_, so only set the last_inset_
1981 // member if the hovered setting is accepted.
1982 d->last_inset_ = inset;
1986 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1987 << d->mouse_position_cache_.x_ << ", "
1988 << d->mouse_position_cache_.y_ << ")");
1990 d->update_strategy_ = DecorationUpdate;
1992 // This event (moving without mouse click) is not passed further.
1993 // This should be changed if it is further utilized.
1994 buffer_.changed(false);
1999 void BufferView::clearLastInset(Inset * inset) const
2001 if (d->last_inset_ != inset) {
2002 LYXERR0("Wrong last_inset!");
2003 LASSERT(false, /**/);
2009 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2011 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2013 // This is only called for mouse related events including
2014 // LFUN_FILE_OPEN generated by drag-and-drop.
2015 FuncRequest cmd = cmd0;
2017 Cursor old = cursor();
2019 cur.push(buffer_.inset());
2020 cur.setSelection(d->cursor_.selection());
2022 // Either the inset under the cursor or the
2023 // surrounding Text will handle this event.
2025 // make sure we stay within the screen...
2026 cmd.set_y(min(max(cmd.y(), -1), height_));
2028 d->mouse_position_cache_.x_ = cmd.x();
2029 d->mouse_position_cache_.y_ = cmd.y();
2031 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2032 updateHoveredInset();
2036 // Build temporary cursor.
2037 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2039 // Put anchor at the same position.
2042 cur.beginUndoGroup();
2044 // Try to dispatch to an non-editable inset near this position
2045 // via the temp cursor. If the inset wishes to change the real
2046 // cursor it has to do so explicitly by using
2047 // cur.bv().cursor() = cur; (or similar)
2049 inset->dispatch(cur, cmd);
2051 // Now dispatch to the temporary cursor. If the real cursor should
2052 // be modified, the inset's dispatch has to do so explicitly.
2053 if (!inset || !cur.result().dispatched())
2058 // Notify left insets
2061 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2063 cursor().fixIfBroken();
2066 // Do we have a selection?
2067 theSelection().haveSelection(cursor().selection());
2069 // If the command has been dispatched,
2070 if (cur.result().dispatched() || cur.result().screenUpdate())
2071 processUpdateFlags(cur.result().screenUpdate());
2075 void BufferView::lfunScroll(FuncRequest const & cmd)
2077 string const scroll_type = cmd.getArg(0);
2078 int scroll_step = 0;
2079 if (scroll_type == "line")
2080 scroll_step = d->scrollbarParameters_.single_step;
2081 else if (scroll_type == "page")
2082 scroll_step = d->scrollbarParameters_.page_step;
2085 string const scroll_quantity = cmd.getArg(1);
2086 if (scroll_quantity == "up")
2087 scrollUp(scroll_step);
2088 else if (scroll_quantity == "down")
2089 scrollDown(scroll_step);
2091 int const scroll_value = convert<int>(scroll_quantity);
2093 scroll(scroll_step * scroll_value);
2095 buffer_.changed(true);
2096 updateHoveredInset();
2100 int BufferView::minVisiblePart()
2102 return 2 * defaultRowHeight();
2106 int BufferView::scroll(int y)
2109 return scrollDown(y);
2111 return scrollUp(-y);
2116 int BufferView::scrollDown(int offset)
2118 Text * text = &buffer_.text();
2119 TextMetrics & tm = d->text_metrics_[text];
2120 int const ymax = height_ + offset;
2122 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2123 int bottom_pos = last.second->position() + last.second->descent();
2124 if (lyxrc.scroll_below_document)
2125 bottom_pos += height_ - minVisiblePart();
2126 if (last.first + 1 == int(text->paragraphs().size())) {
2127 if (bottom_pos <= height_)
2129 offset = min(offset, bottom_pos - height_);
2132 if (bottom_pos > ymax)
2134 tm.newParMetricsDown();
2136 d->anchor_ypos_ -= offset;
2141 int BufferView::scrollUp(int offset)
2143 Text * text = &buffer_.text();
2144 TextMetrics & tm = d->text_metrics_[text];
2145 int ymin = - offset;
2147 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2148 int top_pos = first.second->position() - first.second->ascent();
2149 if (first.first == 0) {
2152 offset = min(offset, - top_pos);
2157 tm.newParMetricsUp();
2159 d->anchor_ypos_ += offset;
2164 void BufferView::setCursorFromRow(int row)
2169 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2173 buffer_.text().setCursor(d->cursor_, 0, 0);
2175 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
2180 bool BufferView::setCursorFromInset(Inset const * inset)
2182 // are we already there?
2183 if (cursor().nextInset() == inset)
2186 // Inset is not at cursor position. Find it in the document.
2189 while (cur && cur.nextInset() != inset)
2200 void BufferView::gotoLabel(docstring const & label)
2202 ListOfBuffers bufs = buffer().allRelatives();
2203 ListOfBuffers::iterator it = bufs.begin();
2204 for (; it != bufs.end(); ++it) {
2205 Buffer const * buf = *it;
2208 Toc & toc = buf->tocBackend().toc("label");
2209 TocIterator toc_it = toc.begin();
2210 TocIterator end = toc.end();
2211 for (; toc_it != end; ++toc_it) {
2212 if (label == toc_it->str()) {
2213 lyx::dispatch(toc_it->action());
2221 TextMetrics const & BufferView::textMetrics(Text const * t) const
2223 return const_cast<BufferView *>(this)->textMetrics(t);
2227 TextMetrics & BufferView::textMetrics(Text const * t)
2229 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2230 if (tmc_it == d->text_metrics_.end()) {
2231 tmc_it = d->text_metrics_.insert(
2232 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2234 return tmc_it->second;
2238 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2241 return textMetrics(t).parMetrics(pit);
2245 int BufferView::workHeight() const
2251 void BufferView::setCursor(DocIterator const & dit)
2254 size_t const n = dit.depth();
2255 for (size_t i = 0; i < n; ++i)
2256 dit[i].inset().edit(d->cursor_, true);
2258 d->cursor_.setCursor(dit);
2259 d->cursor_.setSelection(false);
2263 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2265 // Would be wrong to delete anything if we have a selection.
2266 if (cur.selection())
2269 bool need_anchor_change = false;
2270 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2271 need_anchor_change);
2273 if (need_anchor_change)
2281 cur.forceBufferUpdate();
2282 buffer_.changed(true);
2287 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2289 LASSERT(&cur.bv() == this, /**/);
2292 // this event will clear selection so we save selection for
2293 // persistent selection
2294 cap::saveSelection(cursor());
2296 d->cursor_.macroModeClose();
2298 // Has the cursor just left the inset?
2299 bool leftinset = (&d->cursor_.inset() != &cur.inset());
2301 d->cursor_.fixIfBroken();
2303 // FIXME: shift-mouse selection doesn't work well across insets.
2304 bool do_selection = select && &d->cursor_.normalAnchor().inset() == &cur.inset();
2306 // do the dEPM magic if needed
2307 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2308 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2309 // the leftinset bool would not be necessary (badcursor instead).
2310 bool update = leftinset;
2311 if (!do_selection && d->cursor_.inTexted())
2312 update |= checkDepm(cur, d->cursor_);
2315 d->cursor_.resetAnchor();
2316 d->cursor_.setCursor(cur);
2317 d->cursor_.boundary(cur.boundary());
2319 d->cursor_.setSelection();
2321 d->cursor_.clearSelection();
2323 d->cursor_.finishUndo();
2324 d->cursor_.setCurrentFont();
2326 cur.forceBufferUpdate();
2331 void BufferView::putSelectionAt(DocIterator const & cur,
2332 int length, bool backwards)
2334 d->cursor_.clearSelection();
2340 d->cursor_.pos() += length;
2341 d->cursor_.setSelection(d->cursor_, -length);
2343 d->cursor_.setSelection(d->cursor_, length);
2348 Cursor & BufferView::cursor()
2354 Cursor const & BufferView::cursor() const
2360 pit_type BufferView::anchor_ref() const
2362 return d->anchor_pit_;
2366 bool BufferView::singleParUpdate()
2368 Text & buftext = buffer_.text();
2369 pit_type const bottom_pit = d->cursor_.bottom().pit();
2370 TextMetrics & tm = textMetrics(&buftext);
2371 int old_height = tm.parMetrics(bottom_pit).height();
2373 // make sure inline completion pointer is ok
2374 if (d->inlineCompletionPos_.fixIfBroken())
2375 d->inlineCompletionPos_ = DocIterator();
2377 // In Single Paragraph mode, rebreak only
2378 // the (main text, not inset!) paragraph containing the cursor.
2379 // (if this paragraph contains insets etc., rebreaking will
2380 // recursively descend)
2381 tm.redoParagraph(bottom_pit);
2382 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2383 if (pm.height() != old_height)
2384 // Paragraph height has changed so we cannot proceed to
2385 // the singlePar optimisation.
2388 d->update_strategy_ = SingleParUpdate;
2390 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2391 << " y2: " << pm.position() + pm.descent()
2392 << " pit: " << bottom_pit
2393 << " singlepar: 1");
2398 void BufferView::updateMetrics()
2400 if (height_ == 0 || width_ == 0)
2403 Text & buftext = buffer_.text();
2404 pit_type const npit = int(buftext.paragraphs().size());
2406 // Clear out the position cache in case of full screen redraw,
2407 d->coord_cache_.clear();
2409 // Clear out paragraph metrics to avoid having invalid metrics
2410 // in the cache from paragraphs not relayouted below
2411 // The complete text metrics will be redone.
2412 d->text_metrics_.clear();
2414 TextMetrics & tm = textMetrics(&buftext);
2416 // make sure inline completion pointer is ok
2417 if (d->inlineCompletionPos_.fixIfBroken())
2418 d->inlineCompletionPos_ = DocIterator();
2420 if (d->anchor_pit_ >= npit)
2421 // The anchor pit must have been deleted...
2422 d->anchor_pit_ = npit - 1;
2424 // Rebreak anchor paragraph.
2425 tm.redoParagraph(d->anchor_pit_);
2426 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2429 if (d->anchor_pit_ == 0) {
2430 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2432 // Complete buffer visible? Then it's easy.
2433 if (scrollRange == 0)
2434 d->anchor_ypos_ = anchor_pm.ascent();
2436 // FIXME: Some clever handling needed to show
2437 // the _first_ paragraph up to the top if the cursor is
2438 // in the first line.
2440 anchor_pm.setPosition(d->anchor_ypos_);
2442 LYXERR(Debug::PAINTING, "metrics: "
2443 << " anchor pit = " << d->anchor_pit_
2444 << " anchor ypos = " << d->anchor_ypos_);
2446 // Redo paragraphs above anchor if necessary.
2447 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2448 // We are now just above the anchor paragraph.
2449 pit_type pit1 = d->anchor_pit_ - 1;
2450 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2451 tm.redoParagraph(pit1);
2452 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2454 // Save the paragraph position in the cache.
2459 // Redo paragraphs below the anchor if necessary.
2460 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2461 // We are now just below the anchor paragraph.
2462 pit_type pit2 = d->anchor_pit_ + 1;
2463 for (; pit2 < npit && y2 <= height_; ++pit2) {
2464 tm.redoParagraph(pit2);
2465 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2467 // Save the paragraph position in the cache.
2472 LYXERR(Debug::PAINTING, "Metrics: "
2473 << " anchor pit = " << d->anchor_pit_
2474 << " anchor ypos = " << d->anchor_ypos_
2477 << " pit1 = " << pit1
2478 << " pit2 = " << pit2);
2480 d->update_strategy_ = FullScreenUpdate;
2482 if (lyxerr.debugging(Debug::WORKAREA)) {
2483 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2484 d->coord_cache_.dump();
2489 void BufferView::insertLyXFile(FileName const & fname)
2491 LASSERT(d->cursor_.inTexted(), /**/);
2493 // Get absolute path of file and add ".lyx"
2494 // to the filename if necessary
2495 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2497 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2498 // emit message signal.
2499 message(bformat(_("Inserting document %1$s..."), disp_fn));
2502 Buffer buf("", false);
2503 if (buf.loadLyXFile(filename)) {
2504 ErrorList & el = buffer_.errorList("Parse");
2505 // Copy the inserted document error list into the current buffer one.
2506 el = buf.errorList("Parse");
2507 buffer_.undo().recordUndo(d->cursor_);
2508 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2509 buf.params().documentClassPtr(), el);
2510 res = _("Document %1$s inserted.");
2512 res = _("Could not insert document %1$s");
2515 buffer_.changed(true);
2516 // emit message signal.
2517 message(bformat(res, disp_fn));
2518 buffer_.errors("Parse");
2522 Point BufferView::coordOffset(DocIterator const & dit) const
2528 // Addup contribution of nested insets, from inside to outside,
2529 // keeping the outer paragraph for a special handling below
2530 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2531 CursorSlice const & sl = dit[i];
2535 // get relative position inside sl.inset()
2536 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2538 // Make relative position inside of the edited inset relative to sl.inset()
2542 // In case of an RTL inset, the edited inset will be positioned to the left
2545 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2546 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2551 // remember width for the case that sl.inset() is positioned in an RTL inset
2552 if (i && dit[i - 1].text()) {
2553 // If this Inset is inside a Text Inset, retrieve the Dimension
2554 // from the containing text instead of using Inset::dimension() which
2555 // might not be implemented.
2556 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2557 // elimination of Inset::dim_ cache. This coordOffset() method needs
2558 // to be rewritten in light of the new design.
2559 Dimension const & dim = parMetrics(dit[i - 1].text(),
2560 dit[i - 1].pit()).insetDimension(&sl.inset());
2563 Dimension const dim = sl.inset().dimension(*this);
2567 //lyxerr << "Cursor::getPos, i: "
2568 // << i << " x: " << xx << " y: " << y << endl;
2571 // Add contribution of initial rows of outermost paragraph
2572 CursorSlice const & sl = dit[0];
2573 TextMetrics const & tm = textMetrics(sl.text());
2574 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2575 LASSERT(!pm.rows().empty(), /**/);
2576 y -= pm.rows()[0].ascent();
2578 // FIXME: document this mess
2580 if (sl.pos() > 0 && dit.depth() == 1) {
2582 if (pos && dit.boundary())
2584 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2585 rend = pm.pos2row(pos);
2587 rend = pm.pos2row(sl.pos());
2589 size_t rend = pm.pos2row(sl.pos());
2591 for (size_t rit = 0; rit != rend; ++rit)
2592 y += pm.rows()[rit].height();
2593 y += pm.rows()[rend].ascent();
2595 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2597 // Make relative position from the nested inset now bufferview absolute.
2598 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2601 // In the RTL case place the nested inset at the left of the cursor in
2602 // the outer paragraph
2603 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2604 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2612 Point BufferView::getPos(DocIterator const & dit) const
2614 if (!paragraphVisible(dit))
2615 return Point(-1, -1);
2617 CursorSlice const & bot = dit.bottom();
2618 TextMetrics const & tm = textMetrics(bot.text());
2620 // offset from outer paragraph
2621 Point p = coordOffset(dit);
2622 p.y_ += tm.parMetrics(bot.pit()).position();
2627 bool BufferView::paragraphVisible(DocIterator const & dit) const
2629 CursorSlice const & bot = dit.bottom();
2630 TextMetrics const & tm = textMetrics(bot.text());
2632 return tm.contains(bot.pit());
2636 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2638 Cursor const & cur = cursor();
2639 Font const font = cur.getFont();
2640 frontend::FontMetrics const & fm = theFontMetrics(font);
2641 int const asc = fm.maxAscent();
2642 int const des = fm.maxDescent();
2649 bool BufferView::cursorInView(Point const & p, int h) const
2651 Cursor const & cur = cursor();
2652 // does the cursor touch the screen ?
2653 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2659 void BufferView::draw(frontend::Painter & pain)
2661 if (height_ == 0 || width_ == 0)
2663 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2665 Text & text = buffer_.text();
2666 TextMetrics const & tm = d->text_metrics_[&text];
2667 int const y = tm.first().second->position();
2668 PainterInfo pi(this, pain);
2670 switch (d->update_strategy_) {
2672 case NoScreenUpdate:
2673 // If no screen painting is actually needed, only some the different
2674 // coordinates of insets and paragraphs needs to be updated.
2675 pi.full_repaint = true;
2676 pi.pain.setDrawingEnabled(false);
2680 case SingleParUpdate:
2681 pi.full_repaint = false;
2682 // In general, only the current row of the outermost paragraph
2683 // will be redrawn. Particular cases where selection spans
2684 // multiple paragraph are correctly detected in TextMetrics.
2688 case DecorationUpdate:
2689 // FIXME: We should also distinguish DecorationUpdate to avoid text
2690 // drawing if possible. This is not possible to do easily right now
2691 // because of the single backing pixmap.
2693 case FullScreenUpdate:
2694 // The whole screen, including insets, will be refreshed.
2695 pi.full_repaint = true;
2697 // Clear background.
2698 pain.fillRectangle(0, 0, width_, height_,
2699 pi.backgroundColor(&buffer_.inset()));
2704 // and possibly grey out below
2705 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2706 int const y2 = lastpm.second->position() + lastpm.second->descent();
2709 Color color = buffer().isInternal()
2710 ? Color_background : Color_bottomarea;
2711 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2715 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2717 // The scrollbar needs an update.
2720 // Normalize anchor for next time
2721 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2722 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2723 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2724 ParagraphMetrics const & pm = tm.parMetrics(pit);
2725 if (pm.position() + pm.descent() > 0) {
2726 d->anchor_pit_ = pit;
2727 d->anchor_ypos_ = pm.position();
2731 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2732 << " anchor ypos = " << d->anchor_ypos_);
2736 void BufferView::message(docstring const & msg)
2739 d->gui_->message(msg);
2743 void BufferView::showDialog(string const & name)
2746 d->gui_->showDialog(name, string());
2750 void BufferView::showDialog(string const & name,
2751 string const & data, Inset * inset)
2754 d->gui_->showDialog(name, data, inset);
2758 void BufferView::updateDialog(string const & name, string const & data)
2761 d->gui_->updateDialog(name, data);
2765 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2771 // FIXME: Move this out of BufferView again
2772 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2774 if (!fname.isReadableFile()) {
2775 docstring const error = from_ascii(strerror(errno));
2776 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2777 docstring const text =
2778 bformat(_("Could not read the specified document\n"
2779 "%1$s\ndue to the error: %2$s"), file, error);
2780 Alert::error(_("Could not read file"), text);
2784 if (!fname.isReadableFile()) {
2785 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2786 docstring const text =
2787 bformat(_("%1$s\n is not readable."), file);
2788 Alert::error(_("Could not open file"), text);
2792 // FIXME UNICODE: We don't know the encoding of the file
2793 docstring file_content = fname.fileContents("UTF-8");
2794 if (file_content.empty()) {
2795 Alert::error(_("Reading not UTF-8 encoded file"),
2796 _("The file is not UTF-8 encoded.\n"
2797 "It will be read as local 8Bit-encoded.\n"
2798 "If this does not give the correct result\n"
2799 "then please change the encoding of the file\n"
2800 "to UTF-8 with a program other than LyX.\n"));
2801 file_content = fname.fileContents("local8bit");
2804 return normalize_c(file_content);
2808 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2810 docstring const tmpstr = contentsOfPlaintextFile(f);
2815 Cursor & cur = cursor();
2816 cap::replaceSelection(cur);
2817 buffer_.undo().recordUndo(cur);
2819 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2821 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2823 buffer_.changed(true);
2827 docstring const & BufferView::inlineCompletion() const
2829 return d->inlineCompletion_;
2833 size_t const & BufferView::inlineCompletionUniqueChars() const
2835 return d->inlineCompletionUniqueChars_;
2839 DocIterator const & BufferView::inlineCompletionPos() const
2841 return d->inlineCompletionPos_;
2845 bool samePar(DocIterator const & a, DocIterator const & b)
2847 if (a.empty() && b.empty())
2849 if (a.empty() || b.empty())
2851 if (a.depth() != b.depth())
2853 return &a.innerParagraph() == &b.innerParagraph();
2857 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2858 docstring const & completion, size_t uniqueChars)
2860 uniqueChars = min(completion.size(), uniqueChars);
2861 bool changed = d->inlineCompletion_ != completion
2862 || d->inlineCompletionUniqueChars_ != uniqueChars;
2863 bool singlePar = true;
2864 d->inlineCompletion_ = completion;
2865 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2867 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2870 DocIterator const & old = d->inlineCompletionPos_;
2872 //lyxerr << "inlineCompletionPos changed" << std::endl;
2873 // old or pos are in another paragraph?
2874 if ((!samePar(cur, pos) && !pos.empty())
2875 || (!samePar(cur, old) && !old.empty())) {
2877 //lyxerr << "different paragraph" << std::endl;
2879 d->inlineCompletionPos_ = pos;
2884 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
2885 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2887 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);