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"
45 #include "MetricsInfo.h"
46 #include "Paragraph.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
51 #include "TextClass.h"
52 #include "TextMetrics.h"
54 #include "TocBackend.h"
56 #include "WordLangTuple.h"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetExternal.h"
61 #include "insets/InsetGraphics.h"
62 #include "insets/InsetRef.h"
63 #include "insets/InsetText.h"
64 #include "insets/InsetNote.h"
66 #include "frontends/alert.h"
67 #include "frontends/Application.h"
68 #include "frontends/Delegates.h"
69 #include "frontends/FontMetrics.h"
70 #include "frontends/Painter.h"
71 #include "frontends/Selection.h"
73 #include "graphics/Previews.h"
75 #include "support/convert.h"
76 #include "support/debug.h"
77 #include "support/ExceptionMessage.h"
78 #include "support/filetools.h"
79 #include "support/gettext.h"
80 #include "support/lstrings.h"
81 #include "support/Package.h"
82 #include "support/types.h"
92 using namespace lyx::support;
96 namespace Alert = frontend::Alert;
100 /// Return an inset of this class if it exists at the current cursor position
102 T * getInsetByCode(Cursor const & cur, InsetCode code)
104 DocIterator it = cur;
105 Inset * inset = it.nextInset();
106 if (inset && inset->lyxCode() == code)
107 return static_cast<T*>(inset);
112 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
115 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
116 docstring const & contents)
118 DocIterator tmpdit = dit;
121 Inset const * inset = tmpdit.nextInset();
123 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
124 && (contents.empty() ||
125 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
129 tmpdit.forwardInset();
136 /// Looks for next inset with one of the given codes.
137 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
141 DocIterator tmpdit = dit;
142 tmpdit.forwardInset();
147 Inset const * inset = tmpdit.nextInset();
149 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
150 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
154 if (!findNextInset(tmpdit, codes, contents)) {
155 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
156 Inset * inset = &tmpdit.bottom().inset();
157 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
158 if (!findNextInset(tmpdit, codes, contents))
170 /// Looks for next inset with the given code
171 void findInset(DocIterator & dit, InsetCode code, bool same_content)
173 findInset(dit, vector<InsetCode>(1, code), same_content);
177 /// Moves cursor to the next inset with one of the given codes.
178 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
181 Cursor tmpcur = bv->cursor();
182 if (!findInset(tmpcur, codes, same_content)) {
183 bv->cursor().message(_("No more insets"));
187 tmpcur.clearSelection();
188 bv->setCursor(tmpcur);
193 /// Moves cursor to the next inset with given code.
194 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
196 gotoInset(bv, vector<InsetCode>(1, code), same_content);
200 /// A map from a Text to the associated text metrics
201 typedef map<Text const *, TextMetrics> TextMetricsCache;
203 enum ScreenUpdateStrategy {
213 /////////////////////////////////////////////////////////////////////
217 /////////////////////////////////////////////////////////////////////
219 struct BufferView::Private
221 Private(BufferView & bv): wh_(0), cursor_(bv),
222 anchor_pit_(0), anchor_ypos_(0),
223 inlineCompletionUniqueChars_(0),
224 last_inset_(0), bookmark_edit_position_(0), 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 // cache for id of the paragraph which was edited the last time
268 int bookmark_edit_position_;
270 mutable TextMetricsCache text_metrics_;
273 /** Not owned, so don't delete.
275 frontend::GuiBufferViewDelegate * gui_;
277 /// Cache for Find Next
278 FuncRequest search_request_cache_;
281 map<string, Inset *> edited_insets_;
285 BufferView::BufferView(Buffer & buf)
286 : width_(0), height_(0), full_screen_(false), buffer_(buf),
287 d(new Private(*this))
289 d->xsel_cache_.set = false;
290 d->intl_.initKeyMapper(lyxrc.use_kbmap);
292 d->cursor_.setBuffer(&buf);
293 d->cursor_.push(buffer_.inset());
294 d->cursor_.resetAnchor();
295 d->cursor_.setCurrentFont();
297 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
298 thePreviews().generateBufferPreviews(buffer_);
302 BufferView::~BufferView()
304 // current buffer is going to be switched-off, save cursor pos
305 // Ideally, the whole cursor stack should be saved, but session
306 // currently can only handle bottom (whole document) level pit and pos.
307 // That is to say, if a cursor is in a nested inset, it will be
308 // restore to the left of the top level inset.
309 LastFilePosSection::FilePos fp;
310 fp.pit = d->cursor_.bottom().pit();
311 fp.pos = d->cursor_.bottom().pos();
312 theSession().lastFilePos().save(buffer_.fileName(), fp);
318 int BufferView::rightMargin() const
320 // The additional test for the case the outliner is opened.
322 !lyxrc.full_screen_limit ||
323 width_ < lyxrc.full_screen_width + 20)
326 return (width_ - lyxrc.full_screen_width) / 2;
330 int BufferView::leftMargin() const
332 return rightMargin();
336 bool BufferView::isTopScreen() const
338 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
342 bool BufferView::isBottomScreen() const
344 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
348 Intl & BufferView::getIntl()
354 Intl const & BufferView::getIntl() const
360 CoordCache & BufferView::coordCache()
362 return d->coord_cache_;
366 CoordCache const & BufferView::coordCache() const
368 return d->coord_cache_;
372 Buffer & BufferView::buffer()
378 Buffer const & BufferView::buffer() const
384 bool BufferView::fitCursor()
386 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
387 frontend::FontMetrics const & fm =
388 theFontMetrics(d->cursor_.getFont().fontInfo());
389 int const asc = fm.maxAscent();
390 int const des = fm.maxDescent();
391 Point const p = getPos(d->cursor_, d->cursor_.boundary());
392 if (p.y_ - asc >= 0 && p.y_ + des < height_)
399 void BufferView::processUpdateFlags(Update::flags flags)
401 // last_inset_ points to the last visited inset. This pointer may become
402 // invalid because of keyboard editing. Since all such operations
403 // causes screen update(), I reset last_inset_ to avoid such a problem.
405 // This is close to a hot-path.
406 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
407 << "[fitcursor = " << (flags & Update::FitCursor)
408 << ", forceupdate = " << (flags & Update::Force)
409 << ", singlepar = " << (flags & Update::SinglePar)
410 << "] buffer: " << &buffer_);
412 buffer_.updateMacros();
414 // Now do the first drawing step if needed. This consists on updating
415 // the CoordCache in updateMetrics().
416 // The second drawing step is done in WorkArea::redraw() if needed.
418 // Case when no explicit update is requested.
420 // no need to redraw anything.
421 d->update_strategy_ = NoScreenUpdate;
425 if (flags == Update::Decoration) {
426 d->update_strategy_ = DecorationUpdate;
431 if (flags == Update::FitCursor
432 || flags == (Update::Decoration | Update::FitCursor)) {
433 // tell the frontend to update the screen if needed.
438 if (flags & Update::Decoration) {
439 d->update_strategy_ = DecorationUpdate;
443 // no screen update is needed.
444 d->update_strategy_ = NoScreenUpdate;
448 bool const full_metrics = flags & Update::Force || !singleParUpdate();
451 // We have to update the full screen metrics.
454 if (!(flags & Update::FitCursor)) {
455 // Nothing to do anymore. Trigger a redraw and return
460 // updateMetrics() does not update paragraph position
461 // This is done at draw() time. So we need a redraw!
465 // The cursor is off screen so ensure it is visible.
472 void BufferView::updateScrollbar()
474 if (height_ == 0 && width_ == 0)
477 // We prefer fixed size line scrolling.
478 d->scrollbarParameters_.single_step = defaultRowHeight();
479 // We prefer full screen page scrolling.
480 d->scrollbarParameters_.page_step = height_;
482 Text & t = buffer_.text();
483 TextMetrics & tm = d->text_metrics_[&t];
485 LYXERR(Debug::GUI, " Updating scrollbar: height: "
486 << t.paragraphs().size()
487 << " curr par: " << d->cursor_.bottom().pit()
488 << " default height " << defaultRowHeight());
490 size_t const parsize = t.paragraphs().size();
491 if (d->par_height_.size() != parsize) {
492 d->par_height_.clear();
493 // FIXME: We assume a default paragraph height of 2 rows. This
494 // should probably be pondered with the screen width.
495 d->par_height_.resize(parsize, defaultRowHeight() * 2);
498 // Look at paragraph heights on-screen
499 pair<pit_type, ParagraphMetrics const *> first = tm.first();
500 pair<pit_type, ParagraphMetrics const *> last = tm.last();
501 for (pit_type pit = first.first; pit <= last.first; ++pit) {
502 d->par_height_[pit] = tm.parMetrics(pit).height();
503 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
504 << d->par_height_[pit]);
507 int top_pos = first.second->position() - first.second->ascent();
508 int bottom_pos = last.second->position() + last.second->descent();
509 bool first_visible = first.first == 0 && top_pos >= 0;
510 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
511 if (first_visible && last_visible) {
512 d->scrollbarParameters_.min = 0;
513 d->scrollbarParameters_.max = 0;
517 d->scrollbarParameters_.min = top_pos;
518 for (size_t i = 0; i != size_t(first.first); ++i)
519 d->scrollbarParameters_.min -= d->par_height_[i];
520 d->scrollbarParameters_.max = bottom_pos;
521 for (size_t i = last.first + 1; i != parsize; ++i)
522 d->scrollbarParameters_.max += d->par_height_[i];
524 d->scrollbarParameters_.position = 0;
525 // The reference is the top position so we remove one page.
526 if (lyxrc.scroll_below_document)
527 d->scrollbarParameters_.max -= minVisiblePart();
529 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
533 ScrollbarParameters const & BufferView::scrollbarParameters() const
535 return d->scrollbarParameters_;
539 docstring BufferView::toolTip(int x, int y) const
541 // Get inset under mouse, if there is one.
542 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
544 // No inset, no tooltip...
546 return covering_inset->toolTip(*this, x, y);
550 docstring BufferView::contextMenu(int x, int y) const
552 //If there is a selection, return the containing inset menu
553 if (d->cursor_.selection())
554 return d->cursor_.inset().contextMenu(*this, x, y);
556 // Get inset under mouse, if there is one.
557 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
559 return covering_inset->contextMenu(*this, x, y);
561 return buffer_.inset().contextMenu(*this, x, y);
565 void BufferView::scrollDocView(int value)
567 int const offset = value - d->scrollbarParameters_.position;
569 // No scrolling at all? No need to redraw anything
573 // If the offset is less than 2 screen height, prefer to scroll instead.
574 if (abs(offset) <= 2 * height_) {
575 d->anchor_ypos_ -= offset;
581 // cut off at the top
582 if (value <= d->scrollbarParameters_.min) {
583 DocIterator dit = doc_iterator_begin(&buffer_);
585 LYXERR(Debug::SCROLLING, "scroll to top");
589 // cut off at the bottom
590 if (value >= d->scrollbarParameters_.max) {
591 DocIterator dit = doc_iterator_end(&buffer_);
594 LYXERR(Debug::SCROLLING, "scroll to bottom");
598 // find paragraph at target position
599 int par_pos = d->scrollbarParameters_.min;
601 for (; i != int(d->par_height_.size()); ++i) {
602 par_pos += d->par_height_[i];
603 if (par_pos >= value)
607 if (par_pos < value) {
608 // It seems we didn't find the correct pit so stay on the safe side and
610 LYXERR0("scrolling position not found!");
611 scrollDocView(d->scrollbarParameters_.max);
615 DocIterator dit = doc_iterator_begin(&buffer_);
617 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
622 // FIXME: this method is not working well.
623 void BufferView::setCursorFromScrollbar()
625 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
627 int const height = 2 * defaultRowHeight();
628 int const first = height;
629 int const last = height_ - height;
631 Cursor const & oldcur = d->cursor_;
633 switch (cursorStatus(oldcur)) {
641 int const y = getPos(oldcur, oldcur.boundary()).y_;
642 newy = min(last, max(y, first));
646 // We reset the cursor because cursorStatus() does not
647 // work when the cursor is within mathed.
649 cur.reset(buffer_.inset());
650 tm.setCursorFromCoordinates(cur, 0, newy);
652 // update the bufferview cursor and notify insets
653 // FIXME: Care about the d->cursor_ flags to redraw if needed
654 Cursor old = d->cursor_;
656 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
658 d->cursor_.fixIfBroken();
662 Change const BufferView::getCurrentChange() const
664 if (!d->cursor_.selection())
665 return Change(Change::UNCHANGED);
667 DocIterator dit = d->cursor_.selectionBegin();
668 return dit.paragraph().lookupChange(dit.pos());
672 // this could be used elsewhere as well?
673 // FIXME: This does not work within mathed!
674 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
676 Point const p = getPos(dit, dit.boundary());
679 if (p.y_ > workHeight())
685 void BufferView::bookmarkEditPosition()
687 // Don't eat cpu time for each keystroke
688 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
691 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
695 void BufferView::saveBookmark(unsigned int idx)
697 // tentatively save bookmark, id and pos will be used to
698 // acturately locate a bookmark in a 'live' lyx session.
699 // pit and pos will be updated with bottom level pit/pos
701 theSession().bookmarks().save(
703 d->cursor_.bottom().pit(),
704 d->cursor_.bottom().pos(),
705 d->cursor_.paragraph().id(),
710 // emit message signal.
711 message(_("Save bookmark"));
715 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
716 int top_id, pos_type top_pos)
718 bool success = false;
721 d->cursor_.clearSelection();
723 // if a valid par_id is given, try it first
724 // This is the case for a 'live' bookmark when unique paragraph ID
725 // is used to track bookmarks.
727 dit = buffer_.getParFromID(top_id);
729 dit.pos() = min(dit.paragraph().size(), top_pos);
730 // Some slices of the iterator may not be
731 // reachable (e.g. closed collapsable inset)
732 // so the dociterator may need to be
733 // shortened. Otherwise, setCursor may crash
734 // lyx when the cursor can not be set to these
736 size_t const n = dit.depth();
737 for (size_t i = 0; i < n; ++i)
738 if (!dit[i].inset().editable()) {
746 // if top_id == 0, or searching through top_id failed
747 // This is the case for a 'restored' bookmark when only bottom
748 // (document level) pit was saved. Because of this, bookmark
749 // restoration is inaccurate. If a bookmark was within an inset,
750 // it will be restored to the left of the outmost inset that contains
752 if (bottom_pit < int(buffer_.paragraphs().size())) {
753 dit = doc_iterator_begin(&buffer_);
755 dit.pit() = bottom_pit;
756 dit.pos() = min(bottom_pos, dit.paragraph().size());
761 // Note: only bottom (document) level pit is set.
763 // set the current font.
764 d->cursor_.setCurrentFont();
765 // To center the screen on this new position we need the
766 // paragraph position which is computed at draw() time.
767 // So we need a redraw!
777 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
779 if (lyxrc.rtl_support) {
780 if (d->cursor_.real_current_font.isRightToLeft()) {
781 if (d->intl_.keymap == Intl::PRIMARY)
782 d->intl_.keyMapSec();
784 if (d->intl_.keymap == Intl::SECONDARY)
785 d->intl_.keyMapPrim();
789 d->intl_.getTransManager().translateAndInsert(c, t, cur);
793 int BufferView::workWidth() const
799 void BufferView::recenter()
801 showCursor(d->cursor_, true);
805 void BufferView::showCursor()
807 showCursor(d->cursor_, false);
811 void BufferView::showCursor(DocIterator const & dit, bool recenter)
813 if (scrollToCursor(dit, recenter))
818 void BufferView::scrollToCursor()
820 scrollToCursor(d->cursor_, false);
824 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
826 // We are not properly started yet, delay until resizing is
831 LYXERR(Debug::SCROLLING, "recentering!");
833 CursorSlice const & bot = dit.bottom();
834 TextMetrics & tm = d->text_metrics_[bot.text()];
836 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
837 int bot_pit = bot.pit();
838 if (bot_pit > max_pit) {
839 // FIXME: Why does this happen?
840 LYXERR0("bottom pit is greater that max pit: "
841 << bot_pit << " > " << max_pit);
845 if (bot_pit == tm.first().first - 1)
846 tm.newParMetricsUp();
847 else if (bot_pit == tm.last().first + 1)
848 tm.newParMetricsDown();
850 if (tm.contains(bot_pit)) {
851 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
852 LASSERT(!pm.rows().empty(), /**/);
853 // FIXME: smooth scrolling doesn't work in mathed.
854 CursorSlice const & cs = dit.innerTextSlice();
855 int offset = coordOffset(dit, dit.boundary()).y_;
856 int ypos = pm.position() + offset;
857 Dimension const & row_dim =
858 pm.getRow(cs.pos(), dit.boundary()).dimension();
861 scrolled = scroll(ypos - height_/2);
862 else if (ypos - row_dim.ascent() < 0)
863 scrolled = scrollUp(- ypos + row_dim.ascent());
864 else if (ypos + row_dim.descent() > height_)
865 scrolled = scrollDown(ypos - height_ + defaultRowHeight() );
867 // else, nothing to do, the cursor is already visible so we just return.
875 // fix inline completion position
876 if (d->inlineCompletionPos_.fixIfBroken())
877 d->inlineCompletionPos_ = DocIterator();
879 tm.redoParagraph(bot_pit);
880 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
881 int offset = coordOffset(dit, dit.boundary()).y_;
883 d->anchor_pit_ = bot_pit;
884 CursorSlice const & cs = dit.innerTextSlice();
885 Dimension const & row_dim =
886 pm.getRow(cs.pos(), dit.boundary()).dimension();
889 d->anchor_ypos_ = height_/2;
890 else if (d->anchor_pit_ == 0)
891 d->anchor_ypos_ = offset + pm.ascent();
892 else if (d->anchor_pit_ == max_pit)
893 d->anchor_ypos_ = height_ - offset - row_dim.descent();
894 else if (offset > height_)
895 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
897 d->anchor_ypos_ = defaultRowHeight() * 2;
904 void BufferView::updateLayout(DocumentClass const * const oldlayout)
906 message(_("Converting document to new document class..."));
908 StableDocIterator backcur(d->cursor_);
909 ErrorList & el = buffer_.errorList("Class Switch");
910 cap::switchBetweenClasses(
911 oldlayout, buffer_.params().documentClassPtr(),
912 static_cast<InsetText &>(buffer_.inset()), el);
914 setCursor(backcur.asDocIterator(&buffer_));
916 buffer_.errors("Class Switch");
917 buffer_.updateLabels();
920 /** Return the change status at cursor position, taking in account the
921 * status at each level of the document iterator (a table in a deleted
922 * footnote is deleted).
923 * When \param outer is true, the top slice is not looked at.
925 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
927 size_t const depth = dit.depth() - (outer ? 1 : 0);
929 for (size_t i = 0 ; i < depth ; ++i) {
930 CursorSlice const & slice = dit[i];
931 if (!slice.inset().inMathed()
932 && slice.pos() < slice.paragraph().size()) {
933 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
934 if (ch != Change::UNCHANGED)
938 return Change::UNCHANGED;
942 static bool getLocalStatus(Cursor cursor, FuncRequest const & cmd, FuncStatus & status)
944 // Try to fix cursor in case it is broken.
945 cursor.fixIfBroken();
947 // This is, of course, a mess. Better create a new doc iterator and use
948 // this in Inset::getStatus. This might require an additional
949 // BufferView * arg, though (which should be avoided)
950 //Cursor safe = *this;
952 for ( ; cursor.depth(); cursor.pop()) {
953 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
954 LASSERT(cursor.idx() <= cursor.lastidx(), /**/);
955 LASSERT(cursor.pit() <= cursor.lastpit(), /**/);
956 LASSERT(cursor.pos() <= cursor.lastpos(), /**/);
958 // The inset's getStatus() will return 'true' if it made
959 // a definitive decision on whether it want to handle the
960 // request or not. The result of this decision is put into
961 // the 'status' parameter.
962 if (cursor.inset().getStatus(cursor, cmd, status)) {
971 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
973 // Can we use a readonly buffer?
974 if (buffer_.isReadonly()
975 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
976 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
977 flag.message(from_utf8(N_("Document is read-only")));
978 flag.setEnabled(false);
981 // Are we in a DELETED change-tracking region?
982 if (lookupChangeType(d->cursor_, true) == Change::DELETED
983 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
984 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
985 flag.message(from_utf8(N_("This portion of the document is deleted.")));
986 flag.setEnabled(false);
990 Cursor & cur = d->cursor_;
992 // Is this a function that acts on inset at point?
993 Inset * inset = cur.nextInset();
994 if (lyxaction.funcHasFlag(cmd.action, LyXAction::AtPoint)
995 && inset && inset->getStatus(cur, cmd, flag))
998 if (getLocalStatus(cur, cmd, flag))
1001 switch (cmd.action) {
1003 // FIXME: This is a bit problematic because we don't check is this is a
1004 // document BufferView or not for these LFUNs. We probably have to
1005 // dispatch both to currentBufferView() and, if that fails,
1006 // to documentBufferView(); same as we do know for current Buffer and
1007 // document Buffer. Ideally those LFUN should go to Buffer as they*
1008 // operate on the full Buffer and the cursor is only needed either for
1009 // an Undo record or to restore a cursor position. But we don't know
1010 // how to do that inside Buffer of course.
1011 case LFUN_BUFFER_PARAMS_APPLY:
1012 case LFUN_LAYOUT_MODULES_CLEAR:
1013 case LFUN_LAYOUT_MODULE_ADD:
1014 case LFUN_LAYOUT_RELOAD:
1015 case LFUN_TEXTCLASS_APPLY:
1016 case LFUN_TEXTCLASS_LOAD:
1017 flag.setEnabled(!buffer_.isReadonly());
1021 flag.setEnabled(buffer_.undo().hasUndoStack());
1024 flag.setEnabled(buffer_.undo().hasRedoStack());
1026 case LFUN_FILE_INSERT:
1027 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1028 case LFUN_FILE_INSERT_PLAINTEXT:
1029 case LFUN_BOOKMARK_SAVE:
1030 // FIXME: Actually, these LFUNS should be moved to Text
1031 flag.setEnabled(cur.inTexted());
1034 case LFUN_FONT_STATE:
1035 case LFUN_LABEL_INSERT:
1036 case LFUN_INFO_INSERT:
1037 case LFUN_INSET_EDIT:
1038 case LFUN_PARAGRAPH_GOTO:
1039 case LFUN_NOTE_NEXT:
1040 case LFUN_REFERENCE_NEXT:
1041 case LFUN_WORD_FIND:
1042 case LFUN_WORD_FIND_FORWARD:
1043 case LFUN_WORD_FIND_BACKWARD:
1044 case LFUN_WORD_FINDADV:
1045 case LFUN_WORD_REPLACE:
1048 case LFUN_MARK_TOGGLE:
1049 case LFUN_SCREEN_RECENTER:
1050 case LFUN_SCREEN_SHOW_CURSOR:
1051 case LFUN_BIBTEX_DATABASE_ADD:
1052 case LFUN_BIBTEX_DATABASE_DEL:
1053 case LFUN_NOTES_MUTATE:
1054 case LFUN_ALL_INSETS_TOGGLE:
1055 case LFUN_STATISTICS:
1056 case LFUN_BRANCH_ADD_INSERT:
1057 case LFUN_KEYMAP_OFF:
1058 case LFUN_KEYMAP_PRIMARY:
1059 case LFUN_KEYMAP_SECONDARY:
1060 case LFUN_KEYMAP_TOGGLE:
1061 flag.setEnabled(true);
1064 case LFUN_REGEXP_MODE:
1065 // FIXME: Test if current WorkArea is the search WorkArea
1066 flag.setEnabled(buffer().isInternal() && !cur.inRegexped());
1069 case LFUN_LABEL_COPY_AS_REF: {
1070 // if there is an inset at cursor, see whether it
1072 Inset * inset = cur.nextInset();
1073 if (!inset || !inset->getStatus(cur, cmd, flag))
1074 flag.setEnabled(false);
1078 case LFUN_NEXT_INSET_MODIFY: {
1079 // this is the real function we want to invoke
1080 FuncRequest tmpcmd = cmd;
1081 tmpcmd.action = LFUN_INSET_MODIFY;
1082 // if there is an inset at cursor, see whether it
1083 // handles the lfun, other start from scratch
1084 Inset * inset = cur.nextInset();
1085 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
1086 flag = lyx::getStatus(tmpcmd);
1090 case LFUN_LABEL_GOTO: {
1091 flag.setEnabled(!cmd.argument().empty()
1092 || getInsetByCode<InsetRef>(cur, REF_CODE));
1096 case LFUN_CHANGES_TRACK:
1097 flag.setEnabled(true);
1098 flag.setOnOff(buffer_.params().trackChanges);
1101 case LFUN_CHANGES_OUTPUT:
1102 flag.setEnabled(true);
1103 flag.setOnOff(buffer_.params().outputChanges);
1106 case LFUN_CHANGES_MERGE:
1107 case LFUN_CHANGE_NEXT:
1108 case LFUN_CHANGE_PREVIOUS:
1109 case LFUN_ALL_CHANGES_ACCEPT:
1110 case LFUN_ALL_CHANGES_REJECT:
1111 // TODO: context-sensitive enabling of LFUNs
1112 // In principle, these command should only be enabled if there
1113 // is a change in the document. However, without proper
1114 // optimizations, this will inevitably result in poor performance.
1115 flag.setEnabled(true);
1118 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1119 flag.setOnOff(buffer_.params().compressed);
1123 case LFUN_SCREEN_UP:
1124 case LFUN_SCREEN_DOWN:
1126 case LFUN_SCREEN_UP_SELECT:
1127 case LFUN_SCREEN_DOWN_SELECT:
1128 flag.setEnabled(true);
1131 case LFUN_LAYOUT_TABULAR:
1132 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1136 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1139 case LFUN_LAYOUT_PARAGRAPH:
1140 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1143 case LFUN_DIALOG_SHOW_NEW_INSET:
1144 // FIXME: this is wrong, but I do not understand the
1146 if (cur.inset().lyxCode() == CAPTION_CODE)
1147 return cur.inset().getStatus(cur, cmd, flag);
1148 // FIXME we should consider passthru paragraphs too.
1149 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1152 case LFUN_CITATION_INSERT: {
1153 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1154 // FIXME: This could turn in a recursive hell.
1155 // Shouldn't we use Buffer::getStatus() instead?
1156 flag.setEnabled(lyx::getStatus(fr).enabled());
1159 case LFUN_INSET_APPLY: {
1160 string const name = cmd.getArg(0);
1161 Inset * inset = editedInset(name);
1163 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1165 if (!inset->getStatus(cur, fr, fs)) {
1166 // Every inset is supposed to handle this
1167 LASSERT(false, break);
1171 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1172 flag |= lyx::getStatus(fr);
1178 flag.setEnabled(false);
1186 Inset * BufferView::editedInset(string const & name) const
1188 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1189 return it == d->edited_insets_.end() ? 0 : it->second;
1193 void BufferView::editInset(string const & name, Inset * inset)
1195 d->edited_insets_[name] = inset;
1199 bool BufferView::dispatch(FuncRequest const & cmd)
1201 //lyxerr << [ cmd = " << cmd << "]" << endl;
1203 // Make sure that the cached BufferView is correct.
1204 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1205 << " arg[" << to_utf8(cmd.argument()) << ']'
1206 << " x[" << cmd.x << ']'
1207 << " y[" << cmd.y << ']'
1208 << " button[" << cmd.button() << ']');
1210 string const argument = to_utf8(cmd.argument());
1211 Cursor & cur = d->cursor_;
1213 // Don't dispatch function that does not apply to internal buffers.
1214 if (buffer_.isInternal() && lyxaction.funcHasFlag(cmd.action, LyXAction::NoInternal))
1217 // We'll set this back to false if need be.
1218 bool dispatched = true;
1219 if (cmd.action != LFUN_UNDO && cmd.action != LFUN_REDO)
1220 buffer_.undo().beginUndoGroup();
1222 switch (cmd.action) {
1224 case LFUN_BUFFER_PARAMS_APPLY: {
1225 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1226 cur.recordUndoFullDocument();
1227 istringstream ss(to_utf8(cmd.argument()));
1230 int const unknown_tokens = buffer_.readHeader(lex);
1231 if (unknown_tokens != 0) {
1232 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1233 << unknown_tokens << " unknown token"
1234 << (unknown_tokens == 1 ? "" : "s"));
1236 updateLayout(oldClass);
1238 // We are most certainly here because of a change in the document
1239 // It is then better to make sure that all dialogs are in sync with
1240 // current document settings.
1241 processUpdateFlags(Update::Force | Update::FitCursor);
1245 case LFUN_LAYOUT_MODULES_CLEAR: {
1246 DocumentClass const * const oldClass =
1247 buffer_.params().documentClassPtr();
1248 cur.recordUndoFullDocument();
1249 buffer_.params().clearLayoutModules();
1250 buffer_.params().makeDocumentClass();
1251 updateLayout(oldClass);
1252 processUpdateFlags(Update::Force | Update::FitCursor);
1256 case LFUN_LAYOUT_MODULE_ADD: {
1257 BufferParams const & params = buffer_.params();
1258 if (!params.moduleCanBeAdded(argument)) {
1259 LYXERR0("Module `" << argument <<
1260 "' cannot be added due to failed requirements or "
1261 "conflicts with installed modules.");
1264 DocumentClass const * const oldClass = params.documentClassPtr();
1265 cur.recordUndoFullDocument();
1266 buffer_.params().addLayoutModule(argument);
1267 buffer_.params().makeDocumentClass();
1268 updateLayout(oldClass);
1269 processUpdateFlags(Update::Force | Update::FitCursor);
1273 case LFUN_TEXTCLASS_APPLY: {
1274 if (!LayoutFileList::get().load(argument, buffer_.temppath()) &&
1275 !LayoutFileList::get().load(argument, buffer_.filePath()))
1278 LayoutFile const * old_layout = buffer_.params().baseClass();
1279 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1281 if (old_layout == new_layout)
1285 //Save the old, possibly modular, layout for use in conversion.
1286 DocumentClass const * const oldDocClass =
1287 buffer_.params().documentClassPtr();
1288 cur.recordUndoFullDocument();
1289 buffer_.params().setBaseClass(argument);
1290 buffer_.params().makeDocumentClass();
1291 updateLayout(oldDocClass);
1292 processUpdateFlags(Update::Force | Update::FitCursor);
1296 case LFUN_TEXTCLASS_LOAD:
1297 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1298 LayoutFileList::get().load(argument, buffer_.filePath());
1301 case LFUN_LAYOUT_RELOAD: {
1302 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1303 LayoutFileIndex bc = buffer_.params().baseClassID();
1304 LayoutFileList::get().reset(bc);
1305 buffer_.params().setBaseClass(bc);
1306 buffer_.params().makeDocumentClass();
1307 updateLayout(oldClass);
1308 processUpdateFlags(Update::Force | Update::FitCursor);
1313 cur.message(_("Undo"));
1314 cur.clearSelection();
1315 if (!cur.textUndo())
1316 cur.message(_("No further undo information"));
1318 processUpdateFlags(Update::Force | Update::FitCursor);
1322 cur.message(_("Redo"));
1323 cur.clearSelection();
1324 if (!cur.textRedo())
1325 cur.message(_("No further redo information"));
1327 processUpdateFlags(Update::Force | Update::FitCursor);
1330 case LFUN_FONT_STATE:
1331 cur.message(cur.currentState());
1334 case LFUN_BOOKMARK_SAVE:
1335 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1338 case LFUN_LABEL_GOTO: {
1339 docstring label = cmd.argument();
1340 if (label.empty()) {
1342 getInsetByCode<InsetRef>(cur, REF_CODE);
1344 label = inset->getParam("reference");
1345 // persistent=false: use temp_bookmark
1354 case LFUN_INSET_EDIT: {
1355 FuncRequest fr(cmd);
1356 // if there is an inset at cursor, see whether it
1358 Inset * inset = cur.nextInset();
1360 inset->dispatch(cur, fr);
1361 // if it did not work, try the underlying inset.
1362 if (!inset || !cur.result().dispatched())
1365 // FIXME I'm adding the last break to solve a crash,
1366 // but that is obviously not right.
1367 if (!cur.result().dispatched())
1368 // It did not work too; no action needed.
1373 case LFUN_PARAGRAPH_GOTO: {
1374 int const id = convert<int>(cmd.getArg(0));
1375 int const pos = convert<int>(cmd.getArg(1));
1377 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1378 b = theBufferList().next(b)) {
1380 DocIterator dit = b->getParFromID(id);
1382 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1386 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1387 << " found in buffer `"
1388 << b->absFileName() << "'.");
1390 if (b == &buffer_) {
1394 processUpdateFlags(Update::Force | Update::FitCursor);
1396 // Switch to other buffer view and resend cmd
1397 theLyXFunc().dispatch(FuncRequest(
1398 LFUN_BUFFER_SWITCH, b->absFileName()));
1399 theLyXFunc().dispatch(cmd);
1406 case LFUN_NOTE_NEXT:
1407 gotoInset(this, NOTE_CODE, false);
1410 case LFUN_REFERENCE_NEXT: {
1411 vector<InsetCode> tmp;
1412 tmp.push_back(LABEL_CODE);
1413 tmp.push_back(REF_CODE);
1414 gotoInset(this, tmp, true);
1418 case LFUN_CHANGES_TRACK:
1419 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1422 case LFUN_CHANGES_OUTPUT:
1423 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1424 if (buffer_.params().outputChanges) {
1425 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1426 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1427 LaTeXFeatures::isAvailable("xcolor");
1429 if (!dvipost && !xcolorulem) {
1430 Alert::warning(_("Changes not shown in LaTeX output"),
1431 _("Changes will not be highlighted in LaTeX output, "
1432 "because neither dvipost nor xcolor/ulem are installed.\n"
1433 "Please install these packages or redefine "
1434 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1435 } else if (!xcolorulem) {
1436 Alert::warning(_("Changes not shown in LaTeX output"),
1437 _("Changes will not be highlighted in LaTeX output "
1438 "when using pdflatex, because xcolor and ulem are not installed.\n"
1439 "Please install both packages or redefine "
1440 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1445 case LFUN_CHANGE_NEXT:
1446 findNextChange(this);
1447 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1448 processUpdateFlags(Update::Force | Update::FitCursor);
1451 case LFUN_CHANGE_PREVIOUS:
1452 findPreviousChange(this);
1453 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1454 processUpdateFlags(Update::Force | Update::FitCursor);
1457 case LFUN_CHANGES_MERGE:
1458 if (findNextChange(this) || findPreviousChange(this)) {
1459 processUpdateFlags(Update::Force | Update::FitCursor);
1460 showDialog("changes");
1464 case LFUN_ALL_CHANGES_ACCEPT:
1465 // select complete document
1466 cur.reset(buffer_.inset());
1467 cur.selHandle(true);
1468 buffer_.text().cursorBottom(cur);
1469 // accept everything in a single step to support atomic undo
1470 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1471 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1472 processUpdateFlags(Update::Force | Update::FitCursor);
1475 case LFUN_ALL_CHANGES_REJECT:
1476 // select complete document
1477 cur.reset(buffer_.inset());
1478 cur.selHandle(true);
1479 buffer_.text().cursorBottom(cur);
1480 // reject everything in a single step to support atomic undo
1481 // Note: reject does not work recursively; the user may have to repeat the operation
1482 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1483 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1484 processUpdateFlags(Update::Force | Update::FitCursor);
1487 case LFUN_WORD_FIND_FORWARD:
1488 case LFUN_WORD_FIND_BACKWARD: {
1489 static docstring last_search;
1490 docstring searched_string;
1492 if (!cmd.argument().empty()) {
1493 last_search = cmd.argument();
1494 searched_string = cmd.argument();
1496 searched_string = last_search;
1499 if (searched_string.empty())
1502 bool const fw = cmd.action == LFUN_WORD_FIND_FORWARD;
1503 docstring const data =
1504 find2string(searched_string, true, false, fw);
1505 find(this, FuncRequest(LFUN_WORD_FIND, data));
1509 case LFUN_WORD_FIND: {
1510 FuncRequest req = cmd;
1511 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1512 req = d->search_request_cache_;
1513 if (req.argument().empty()) {
1514 theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1517 if (find(this, req))
1520 message(_("String not found!"));
1521 d->search_request_cache_ = req;
1525 case LFUN_WORD_REPLACE: {
1526 bool has_deleted = false;
1527 if (cur.selection()) {
1528 DocIterator beg = cur.selectionBegin();
1529 DocIterator end = cur.selectionEnd();
1530 if (beg.pit() == end.pit()) {
1531 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1532 if (cur.paragraph().isDeleted(p))
1537 replace(this, cmd, has_deleted);
1541 case LFUN_WORD_FINDADV:
1546 cur.clearSelection();
1547 cur.message(from_utf8(N_("Mark off")));
1551 cur.clearSelection();
1553 cur.message(from_utf8(N_("Mark on")));
1556 case LFUN_MARK_TOGGLE:
1557 cur.setSelection(false);
1560 cur.message(from_utf8(N_("Mark removed")));
1563 cur.message(from_utf8(N_("Mark set")));
1568 case LFUN_SCREEN_SHOW_CURSOR:
1572 case LFUN_SCREEN_RECENTER:
1576 case LFUN_BIBTEX_DATABASE_ADD: {
1577 Cursor tmpcur = cur;
1578 findInset(tmpcur, BIBTEX_CODE, false);
1579 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1582 if (inset->addDatabase(cmd.argument()))
1583 buffer_.updateBibfilesCache();
1588 case LFUN_BIBTEX_DATABASE_DEL: {
1589 Cursor tmpcur = cur;
1590 findInset(tmpcur, BIBTEX_CODE, false);
1591 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1594 if (inset->delDatabase(cmd.argument()))
1595 buffer_.updateBibfilesCache();
1600 case LFUN_STATISTICS: {
1601 DocIterator from, to;
1602 if (cur.selection()) {
1603 from = cur.selectionBegin();
1604 to = cur.selectionEnd();
1606 from = doc_iterator_begin(&buffer_);
1607 to = doc_iterator_end(&buffer_);
1609 int const words = countWords(from, to);
1610 int const chars = countChars(from, to, false);
1611 int const chars_blanks = countChars(from, to, true);
1613 if (cur.selection())
1614 message = _("Statistics for the selection:");
1616 message = _("Statistics for the document:");
1619 message += bformat(_("%1$d words"), words);
1621 message += _("One word");
1623 if (chars_blanks != 1)
1624 message += bformat(_("%1$d characters (including blanks)"),
1627 message += _("One character (including blanks)");
1630 message += bformat(_("%1$d characters (excluding blanks)"),
1633 message += _("One character (excluding blanks)");
1635 Alert::information(_("Statistics"), message);
1639 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1640 // turn compression on/off
1641 buffer_.params().compressed = !buffer_.params().compressed;
1644 case LFUN_LABEL_COPY_AS_REF: {
1645 // if there is an inset at cursor, try to copy it
1646 Inset * inset = &cur.inset();
1647 if (!inset || !inset->asInsetMath())
1648 inset = cur.nextInset();
1650 FuncRequest tmpcmd = cmd;
1651 inset->dispatch(cur, tmpcmd);
1653 if (!cur.result().dispatched())
1654 // It did not work too; no action needed.
1656 cur.clearSelection();
1657 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1661 case LFUN_NEXT_INSET_MODIFY: {
1662 // create the the real function we want to invoke
1663 FuncRequest tmpcmd = cmd;
1664 tmpcmd.action = LFUN_INSET_MODIFY;
1665 // if there is an inset at cursor, see whether it
1667 Inset * inset = cur.nextInset();
1670 inset->dispatch(cur, tmpcmd);
1672 // if it did not work, try the underlying inset.
1673 if (!inset || !cur.result().dispatched()) {
1675 cur.dispatch(tmpcmd);
1678 if (!cur.result().dispatched())
1679 // It did not work too; no action needed.
1681 cur.clearSelection();
1682 processUpdateFlags(Update::Force | Update::FitCursor);
1686 case LFUN_SCREEN_UP:
1687 case LFUN_SCREEN_DOWN: {
1688 Point p = getPos(cur, cur.boundary());
1689 // This code has been commented out to enable to scroll down a
1690 // document, even if there are large insets in it (see bug #5465).
1691 /*if (p.y_ < 0 || p.y_ > height_) {
1692 // The cursor is off-screen so recenter before proceeding.
1694 p = getPos(cur, cur.boundary());
1696 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1697 ? -height_ : height_);
1698 if (cmd.action == LFUN_SCREEN_UP && scrolled > -height_)
1700 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1701 p = Point(width_, height_);
1703 bool const in_texted = cur.inTexted();
1704 cur.reset(buffer_.inset());
1707 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1708 true, cmd.action == LFUN_SCREEN_UP);
1709 //FIXME: what to do with cur.x_target()?
1710 bool update = in_texted && cur.bv().checkDepm(cur, old);
1713 processUpdateFlags(Update::Force | Update::FitCursor);
1721 case LFUN_SCREEN_UP_SELECT: {
1722 cur.selHandle(true);
1723 if (isTopScreen()) {
1724 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1728 int y = getPos(cur, cur.boundary()).y_;
1729 int const ymin = y - height_ + defaultRowHeight();
1730 while (y > ymin && cur.up())
1731 y = getPos(cur, cur.boundary()).y_;
1734 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1738 case LFUN_SCREEN_DOWN_SELECT: {
1739 cur.selHandle(true);
1740 if (isBottomScreen()) {
1741 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1745 int y = getPos(cur, cur.boundary()).y_;
1746 int const ymax = y + height_ - defaultRowHeight();
1747 while (y < ymax && cur.down())
1748 y = getPos(cur, cur.boundary()).y_;
1751 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1755 // This could be rewriten using some command like forall <insetname> <command>
1756 // once the insets refactoring is done.
1757 case LFUN_NOTES_MUTATE: {
1758 if (cmd.argument().empty())
1761 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1762 processUpdateFlags(Update::Force);
1767 case LFUN_ALL_INSETS_TOGGLE: {
1769 string const name = split(to_utf8(cmd.argument()), action, ' ');
1770 InsetCode const inset_code = insetCode(name);
1772 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1774 Inset & inset = cur.buffer()->inset();
1775 InsetIterator it = inset_iterator_begin(inset);
1776 InsetIterator const end = inset_iterator_end(inset);
1777 for (; it != end; ++it) {
1778 if (it->asInsetCollapsable()
1779 && (inset_code == NO_CODE
1780 || inset_code == it->lyxCode())) {
1781 Cursor tmpcur = cur;
1782 tmpcur.pushBackward(*it);
1783 it->dispatch(tmpcur, fr);
1786 processUpdateFlags(Update::Force | Update::FitCursor);
1790 case LFUN_BRANCH_ADD_INSERT: {
1791 docstring branch_name = from_utf8(cmd.getArg(0));
1792 if (branch_name.empty())
1793 if (!Alert::askForText(branch_name, _("Branch name")) ||
1794 branch_name.empty())
1797 DispatchResult drtmp;
1798 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1799 if (drtmp.error()) {
1800 Alert::warning(_("Branch already exists"), drtmp.message());
1803 BranchList & branch_list = buffer_.params().branchlist();
1804 Branch const * branch = branch_list.find(branch_name);
1805 string const x11hexname = X11hexname(branch->color());
1806 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1807 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1808 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1812 case LFUN_KEYMAP_OFF:
1813 getIntl().keyMapOn(false);
1816 case LFUN_KEYMAP_PRIMARY:
1817 getIntl().keyMapPrim();
1820 case LFUN_KEYMAP_SECONDARY:
1821 getIntl().keyMapSec();
1824 case LFUN_KEYMAP_TOGGLE:
1825 getIntl().toggleKeyMap();
1828 case LFUN_DIALOG_SHOW_NEW_INSET: {
1829 string const name = cmd.getArg(0);
1830 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1831 if (decodeInsetParam(name, data, buffer_))
1832 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1834 lyxerr << "Inset type '" << name <<
1835 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1839 case LFUN_CITATION_INSERT: {
1840 if (argument.empty()) {
1841 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1844 // we can have one optional argument, delimited by '|'
1845 // citation-insert <key>|<text_before>
1846 // this should be enhanced to also support text_after
1847 // and citation style
1848 string arg = argument;
1850 if (contains(argument, "|")) {
1851 arg = token(argument, '|', 0);
1852 opt1 = token(argument, '|', 1);
1854 InsetCommandParams icp(CITE_CODE);
1855 icp["key"] = from_utf8(arg);
1857 icp["before"] = from_utf8(opt1);
1858 string icstr = InsetCommand::params2string("citation", icp);
1859 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1864 case LFUN_INSET_APPLY: {
1865 string const name = cmd.getArg(0);
1866 Inset * inset = editedInset(name);
1868 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1872 // put cursor in front of inset.
1873 if (!setCursorFromInset(inset)) {
1874 LASSERT(false, break);
1877 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1878 inset->dispatch(cur, fr);
1879 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1888 if (cmd.action != LFUN_UNDO && cmd.action != LFUN_REDO)
1889 buffer_.undo().endUndoGroup();
1894 docstring const BufferView::requestSelection()
1896 Cursor & cur = d->cursor_;
1898 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1899 if (!cur.selection()) {
1900 d->xsel_cache_.set = false;
1904 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1905 if (!d->xsel_cache_.set ||
1906 cur.top() != d->xsel_cache_.cursor ||
1907 cur.anchor_.top() != d->xsel_cache_.anchor)
1909 d->xsel_cache_.cursor = cur.top();
1910 d->xsel_cache_.anchor = cur.anchor_.top();
1911 d->xsel_cache_.set = cur.selection();
1912 return cur.selectionAsString(false);
1918 void BufferView::clearSelection()
1920 d->cursor_.clearSelection();
1921 // Clear the selection buffer. Otherwise a subsequent
1922 // middle-mouse-button paste would use the selection buffer,
1923 // not the more current external selection.
1924 cap::clearSelection();
1925 d->xsel_cache_.set = false;
1926 // The buffer did not really change, but this causes the
1927 // redraw we need because we cleared the selection above.
1932 void BufferView::resize(int width, int height)
1934 // Update from work area
1938 // Clear the paragraph height cache.
1939 d->par_height_.clear();
1940 // Redo the metrics.
1945 Inset const * BufferView::getCoveringInset(Text const & text,
1948 TextMetrics & tm = d->text_metrics_[&text];
1949 Inset * inset = tm.checkInsetHit(x, y);
1953 if (!inset->descendable())
1954 // No need to go further down if the inset is not
1958 size_t cell_number = inset->nargs();
1959 // Check all the inner cell.
1960 for (size_t i = 0; i != cell_number; ++i) {
1961 Text const * inner_text = inset->getText(i);
1964 Inset const * inset_deeper =
1965 getCoveringInset(*inner_text, x, y);
1967 return inset_deeper;
1975 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1977 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1979 // This is only called for mouse related events including
1980 // LFUN_FILE_OPEN generated by drag-and-drop.
1981 FuncRequest cmd = cmd0;
1983 Cursor old = cursor();
1985 cur.push(buffer_.inset());
1986 cur.setSelection(d->cursor_.selection());
1988 // Either the inset under the cursor or the
1989 // surrounding Text will handle this event.
1991 // make sure we stay within the screen...
1992 cmd.y = min(max(cmd.y, -1), height_);
1994 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1996 // Get inset under mouse, if there is one.
1997 Inset const * covering_inset =
1998 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1999 if (covering_inset == d->last_inset_)
2000 // Same inset, no need to do anything...
2003 bool need_redraw = false;
2004 // const_cast because of setMouseHover().
2005 Inset * inset = const_cast<Inset *>(covering_inset);
2007 // Remove the hint on the last hovered inset (if any).
2008 need_redraw |= d->last_inset_->setMouseHover(false);
2010 // Highlighted the newly hovered inset (if any).
2011 need_redraw |= inset->setMouseHover(true);
2012 d->last_inset_ = inset;
2016 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2017 << cmd.x << ", " << cmd.y << ")");
2019 d->update_strategy_ = DecorationUpdate;
2021 // This event (moving without mouse click) is not passed further.
2022 // This should be changed if it is further utilized.
2027 // Build temporary cursor.
2028 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
2030 // Put anchor at the same position.
2033 cur.beginUndoGroup();
2035 // Try to dispatch to an non-editable inset near this position
2036 // via the temp cursor. If the inset wishes to change the real
2037 // cursor it has to do so explicitly by using
2038 // cur.bv().cursor() = cur; (or similar)
2040 inset->dispatch(cur, cmd);
2042 // Now dispatch to the temporary cursor. If the real cursor should
2043 // be modified, the inset's dispatch has to do so explicitly.
2044 if (!inset || !cur.result().dispatched())
2049 // Notify left insets
2052 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2054 cursor().fixIfBroken();
2057 // Do we have a selection?
2058 theSelection().haveSelection(cursor().selection());
2060 // If the command has been dispatched,
2061 if (cur.result().dispatched() || cur.result().update())
2062 processUpdateFlags(cur.result().update());
2066 void BufferView::lfunScroll(FuncRequest const & cmd)
2068 string const scroll_type = cmd.getArg(0);
2069 int const scroll_step =
2070 (scroll_type == "line") ? d->scrollbarParameters_.single_step
2071 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
2072 if (scroll_step == 0)
2074 string const scroll_quantity = cmd.getArg(1);
2075 if (scroll_quantity == "up")
2076 scrollUp(scroll_step);
2077 else if (scroll_quantity == "down")
2078 scrollDown(scroll_step);
2080 int const scroll_value = convert<int>(scroll_quantity);
2082 scroll(scroll_step * scroll_value);
2089 int BufferView::minVisiblePart()
2091 return 2 * defaultRowHeight();
2095 int BufferView::scroll(int y)
2098 return scrollDown(y);
2100 return scrollUp(-y);
2105 int BufferView::scrollDown(int offset)
2107 Text * text = &buffer_.text();
2108 TextMetrics & tm = d->text_metrics_[text];
2109 int const ymax = height_ + offset;
2111 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2112 int bottom_pos = last.second->position() + last.second->descent();
2113 if (lyxrc.scroll_below_document)
2114 bottom_pos += height_ - minVisiblePart();
2115 if (last.first + 1 == int(text->paragraphs().size())) {
2116 if (bottom_pos <= height_)
2118 offset = min(offset, bottom_pos - height_);
2121 if (bottom_pos > ymax)
2123 tm.newParMetricsDown();
2125 d->anchor_ypos_ -= offset;
2130 int BufferView::scrollUp(int offset)
2132 Text * text = &buffer_.text();
2133 TextMetrics & tm = d->text_metrics_[text];
2134 int ymin = - offset;
2136 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2137 int top_pos = first.second->position() - first.second->ascent();
2138 if (first.first == 0) {
2141 offset = min(offset, - top_pos);
2146 tm.newParMetricsUp();
2148 d->anchor_ypos_ += offset;
2153 void BufferView::setCursorFromRow(int row)
2158 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2160 d->cursor_.reset(buffer_.inset());
2162 buffer_.text().setCursor(d->cursor_, 0, 0);
2164 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
2169 bool BufferView::setCursorFromInset(Inset const * inset)
2171 // are we already there?
2172 if (cursor().nextInset() == inset)
2175 // Inset is not at cursor position. Find it in the document.
2177 cur.reset(buffer().inset());
2178 while (cur && cur.nextInset() != inset)
2189 void BufferView::gotoLabel(docstring const & label)
2191 std::vector<Buffer const *> bufs = buffer().allRelatives();
2192 std::vector<Buffer const *>::iterator it = bufs.begin();
2193 for (; it != bufs.end(); ++it) {
2194 Buffer const * buf = *it;
2197 Toc & toc = buf->tocBackend().toc("label");
2198 TocIterator toc_it = toc.begin();
2199 TocIterator end = toc.end();
2200 for (; toc_it != end; ++toc_it) {
2201 if (label == toc_it->str()) {
2202 dispatch(toc_it->action());
2210 TextMetrics const & BufferView::textMetrics(Text const * t) const
2212 return const_cast<BufferView *>(this)->textMetrics(t);
2216 TextMetrics & BufferView::textMetrics(Text const * t)
2218 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2219 if (tmc_it == d->text_metrics_.end()) {
2220 tmc_it = d->text_metrics_.insert(
2221 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2223 return tmc_it->second;
2227 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2230 return textMetrics(t).parMetrics(pit);
2234 int BufferView::workHeight() const
2240 void BufferView::setCursor(DocIterator const & dit)
2242 d->cursor_.reset(buffer().inset());
2243 size_t const n = dit.depth();
2244 for (size_t i = 0; i < n; ++i)
2245 dit[i].inset().edit(d->cursor_, true);
2247 d->cursor_.setCursor(dit);
2248 d->cursor_.setSelection(false);
2252 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2254 // Would be wrong to delete anything if we have a selection.
2255 if (cur.selection())
2258 bool need_anchor_change = false;
2259 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2260 need_anchor_change);
2262 if (need_anchor_change)
2270 buffer_.updateLabels();
2278 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2280 LASSERT(&cur.bv() == this, /**/);
2283 // this event will clear selection so we save selection for
2284 // persistent selection
2285 cap::saveSelection(cursor());
2287 // Has the cursor just left the inset?
2288 bool leftinset = (&d->cursor_.inset() != &cur.inset());
2290 d->cursor_.fixIfBroken();
2292 // FIXME: shift-mouse selection doesn't work well across insets.
2293 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
2295 // do the dEPM magic if needed
2296 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2297 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2298 // the leftinset bool would not be necessary (badcursor instead).
2299 bool update = leftinset;
2300 if (!do_selection && d->cursor_.inTexted())
2301 update |= checkDepm(cur, d->cursor_);
2302 d->cursor_.macroModeClose();
2304 d->cursor_.resetAnchor();
2305 d->cursor_.setCursor(cur);
2306 d->cursor_.boundary(cur.boundary());
2308 d->cursor_.setSelection();
2310 d->cursor_.clearSelection();
2312 d->cursor_.finishUndo();
2313 d->cursor_.setCurrentFont();
2318 void BufferView::putSelectionAt(DocIterator const & cur,
2319 int length, bool backwards)
2321 d->cursor_.clearSelection();
2327 d->cursor_.pos() += length;
2328 d->cursor_.setSelection(d->cursor_, -length);
2330 d->cursor_.setSelection(d->cursor_, length);
2332 // Ensure a redraw happens in any case because the new selection could
2333 // possibly be on the same screen as the previous selection.
2334 processUpdateFlags(Update::Force | Update::FitCursor);
2338 Cursor & BufferView::cursor()
2344 Cursor const & BufferView::cursor() const
2350 pit_type BufferView::anchor_ref() const
2352 return d->anchor_pit_;
2356 bool BufferView::singleParUpdate()
2358 Text & buftext = buffer_.text();
2359 pit_type const bottom_pit = d->cursor_.bottom().pit();
2360 TextMetrics & tm = textMetrics(&buftext);
2361 int old_height = tm.parMetrics(bottom_pit).height();
2363 // make sure inline completion pointer is ok
2364 if (d->inlineCompletionPos_.fixIfBroken())
2365 d->inlineCompletionPos_ = DocIterator();
2367 // In Single Paragraph mode, rebreak only
2368 // the (main text, not inset!) paragraph containing the cursor.
2369 // (if this paragraph contains insets etc., rebreaking will
2370 // recursively descend)
2371 tm.redoParagraph(bottom_pit);
2372 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2373 if (pm.height() != old_height)
2374 // Paragraph height has changed so we cannot proceed to
2375 // the singlePar optimisation.
2378 d->update_strategy_ = SingleParUpdate;
2380 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2381 << " y2: " << pm.position() + pm.descent()
2382 << " pit: " << bottom_pit
2383 << " singlepar: 1");
2388 void BufferView::updateMetrics()
2390 if (height_ == 0 || width_ == 0)
2393 Text & buftext = buffer_.text();
2394 pit_type const npit = int(buftext.paragraphs().size());
2396 // Clear out the position cache in case of full screen redraw,
2397 d->coord_cache_.clear();
2399 // Clear out paragraph metrics to avoid having invalid metrics
2400 // in the cache from paragraphs not relayouted below
2401 // The complete text metrics will be redone.
2402 d->text_metrics_.clear();
2404 TextMetrics & tm = textMetrics(&buftext);
2406 // make sure inline completion pointer is ok
2407 if (d->inlineCompletionPos_.fixIfBroken())
2408 d->inlineCompletionPos_ = DocIterator();
2410 if (d->anchor_pit_ >= npit)
2411 // The anchor pit must have been deleted...
2412 d->anchor_pit_ = npit - 1;
2414 // Rebreak anchor paragraph.
2415 tm.redoParagraph(d->anchor_pit_);
2416 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2419 if (d->anchor_pit_ == 0) {
2420 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2422 // Complete buffer visible? Then it's easy.
2423 if (scrollRange == 0)
2424 d->anchor_ypos_ = anchor_pm.ascent();
2426 // FIXME: Some clever handling needed to show
2427 // the _first_ paragraph up to the top if the cursor is
2428 // in the first line.
2430 anchor_pm.setPosition(d->anchor_ypos_);
2432 LYXERR(Debug::PAINTING, "metrics: "
2433 << " anchor pit = " << d->anchor_pit_
2434 << " anchor ypos = " << d->anchor_ypos_);
2436 // Redo paragraphs above anchor if necessary.
2437 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2438 // We are now just above the anchor paragraph.
2439 pit_type pit1 = d->anchor_pit_ - 1;
2440 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2441 tm.redoParagraph(pit1);
2442 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2444 // Save the paragraph position in the cache.
2449 // Redo paragraphs below the anchor if necessary.
2450 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2451 // We are now just below the anchor paragraph.
2452 pit_type pit2 = d->anchor_pit_ + 1;
2453 for (; pit2 < npit && y2 <= height_; ++pit2) {
2454 tm.redoParagraph(pit2);
2455 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2457 // Save the paragraph position in the cache.
2462 LYXERR(Debug::PAINTING, "Metrics: "
2463 << " anchor pit = " << d->anchor_pit_
2464 << " anchor ypos = " << d->anchor_ypos_
2467 << " pit1 = " << pit1
2468 << " pit2 = " << pit2);
2470 d->update_strategy_ = FullScreenUpdate;
2472 if (lyxerr.debugging(Debug::WORKAREA)) {
2473 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2474 d->coord_cache_.dump();
2479 void BufferView::insertLyXFile(FileName const & fname)
2481 LASSERT(d->cursor_.inTexted(), /**/);
2483 // Get absolute path of file and add ".lyx"
2484 // to the filename if necessary
2485 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2487 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2488 // emit message signal.
2489 message(bformat(_("Inserting document %1$s..."), disp_fn));
2492 Buffer buf("", false);
2493 if (buf.loadLyXFile(filename)) {
2494 ErrorList & el = buffer_.errorList("Parse");
2495 // Copy the inserted document error list into the current buffer one.
2496 el = buf.errorList("Parse");
2497 buffer_.undo().recordUndo(d->cursor_);
2498 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2499 buf.params().documentClassPtr(), el);
2500 res = _("Document %1$s inserted.");
2502 res = _("Could not insert document %1$s");
2507 // emit message signal.
2508 message(bformat(res, disp_fn));
2509 buffer_.errors("Parse");
2513 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2519 // Addup contribution of nested insets, from inside to outside,
2520 // keeping the outer paragraph for a special handling below
2521 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2522 CursorSlice const & sl = dit[i];
2526 // get relative position inside sl.inset()
2527 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2529 // Make relative position inside of the edited inset relative to sl.inset()
2533 // In case of an RTL inset, the edited inset will be positioned to the left
2536 bool boundary_i = boundary && i + 1 == dit.depth();
2537 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2542 // remember width for the case that sl.inset() is positioned in an RTL inset
2543 if (i && dit[i - 1].text()) {
2544 // If this Inset is inside a Text Inset, retrieve the Dimension
2545 // from the containing text instead of using Inset::dimension() which
2546 // might not be implemented.
2547 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2548 // elimination of Inset::dim_ cache. This coordOffset() method needs
2549 // to be rewritten in light of the new design.
2550 Dimension const & dim = parMetrics(dit[i - 1].text(),
2551 dit[i - 1].pit()).insetDimension(&sl.inset());
2554 Dimension const dim = sl.inset().dimension(*this);
2558 //lyxerr << "Cursor::getPos, i: "
2559 // << i << " x: " << xx << " y: " << y << endl;
2562 // Add contribution of initial rows of outermost paragraph
2563 CursorSlice const & sl = dit[0];
2564 TextMetrics const & tm = textMetrics(sl.text());
2565 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2566 LASSERT(!pm.rows().empty(), /**/);
2567 y -= pm.rows()[0].ascent();
2569 // FIXME: document this mess
2571 if (sl.pos() > 0 && dit.depth() == 1) {
2573 if (pos && boundary)
2575 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2576 rend = pm.pos2row(pos);
2578 rend = pm.pos2row(sl.pos());
2580 size_t rend = pm.pos2row(sl.pos());
2582 for (size_t rit = 0; rit != rend; ++rit)
2583 y += pm.rows()[rit].height();
2584 y += pm.rows()[rend].ascent();
2586 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2588 // Make relative position from the nested inset now bufferview absolute.
2589 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2592 // In the RTL case place the nested inset at the left of the cursor in
2593 // the outer paragraph
2594 bool boundary_1 = boundary && 1 == dit.depth();
2595 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2603 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2605 if (!paragraphVisible(dit))
2606 return Point(-1, -1);
2608 CursorSlice const & bot = dit.bottom();
2609 TextMetrics const & tm = textMetrics(bot.text());
2611 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2612 p.y_ += tm.parMetrics(bot.pit()).position();
2617 bool BufferView::paragraphVisible(DocIterator const & dit) const
2619 CursorSlice const & bot = dit.bottom();
2620 TextMetrics const & tm = textMetrics(bot.text());
2622 return tm.contains(bot.pit());
2626 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2628 Cursor const & cur = cursor();
2629 Font const font = cur.getFont();
2630 frontend::FontMetrics const & fm = theFontMetrics(font);
2631 int const asc = fm.maxAscent();
2632 int const des = fm.maxDescent();
2634 p = getPos(cur, cur.boundary());
2639 bool BufferView::cursorInView(Point const & p, int h) const
2641 Cursor const & cur = cursor();
2642 // does the cursor touch the screen ?
2643 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2649 void BufferView::draw(frontend::Painter & pain)
2651 if (height_ == 0 || width_ == 0)
2653 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2655 Text & text = buffer_.text();
2656 TextMetrics const & tm = d->text_metrics_[&text];
2657 int const y = tm.first().second->position();
2658 PainterInfo pi(this, pain);
2660 switch (d->update_strategy_) {
2662 case NoScreenUpdate:
2663 // If no screen painting is actually needed, only some the different
2664 // coordinates of insets and paragraphs needs to be updated.
2665 pi.full_repaint = true;
2666 pi.pain.setDrawingEnabled(false);
2670 case SingleParUpdate:
2671 pi.full_repaint = false;
2672 // In general, only the current row of the outermost paragraph
2673 // will be redrawn. Particular cases where selection spans
2674 // multiple paragraph are correctly detected in TextMetrics.
2678 case DecorationUpdate:
2679 // FIXME: We should also distinguish DecorationUpdate to avoid text
2680 // drawing if possible. This is not possible to do easily right now
2681 // because of the single backing pixmap.
2683 case FullScreenUpdate:
2684 // The whole screen, including insets, will be refreshed.
2685 pi.full_repaint = true;
2687 // Clear background.
2688 pain.fillRectangle(0, 0, width_, height_,
2689 pi.backgroundColor(&buffer_.inset()));
2694 // and possibly grey out below
2695 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2696 int const y2 = lastpm.second->position() + lastpm.second->descent();
2699 Color color = buffer().isInternal()
2700 ? Color_background : Color_bottomarea;
2701 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2705 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2707 // The scrollbar needs an update.
2710 // Normalize anchor for next time
2711 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2712 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2713 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2714 ParagraphMetrics const & pm = tm.parMetrics(pit);
2715 if (pm.position() + pm.descent() > 0) {
2716 d->anchor_pit_ = pit;
2717 d->anchor_ypos_ = pm.position();
2721 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2722 << " anchor ypos = " << d->anchor_ypos_);
2726 void BufferView::message(docstring const & msg)
2729 d->gui_->message(msg);
2733 void BufferView::showDialog(string const & name)
2736 d->gui_->showDialog(name, string());
2740 void BufferView::showDialog(string const & name,
2741 string const & data, Inset * inset)
2744 d->gui_->showDialog(name, data, inset);
2748 void BufferView::updateDialog(string const & name, string const & data)
2751 d->gui_->updateDialog(name, data);
2755 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2761 // FIXME: Move this out of BufferView again
2762 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2764 if (!fname.isReadableFile()) {
2765 docstring const error = from_ascii(strerror(errno));
2766 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2767 docstring const text =
2768 bformat(_("Could not read the specified document\n"
2769 "%1$s\ndue to the error: %2$s"), file, error);
2770 Alert::error(_("Could not read file"), text);
2774 if (!fname.isReadableFile()) {
2775 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2776 docstring const text =
2777 bformat(_("%1$s\n is not readable."), file);
2778 Alert::error(_("Could not open file"), text);
2782 // FIXME UNICODE: We don't know the encoding of the file
2783 docstring file_content = fname.fileContents("UTF-8");
2784 if (file_content.empty()) {
2785 Alert::error(_("Reading not UTF-8 encoded file"),
2786 _("The file is not UTF-8 encoded.\n"
2787 "It will be read as local 8Bit-encoded.\n"
2788 "If this does not give the correct result\n"
2789 "then please change the encoding of the file\n"
2790 "to UTF-8 with a program other than LyX.\n"));
2791 file_content = fname.fileContents("local8bit");
2794 return normalize_c(file_content);
2798 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2800 docstring const tmpstr = contentsOfPlaintextFile(f);
2805 Cursor & cur = cursor();
2806 cap::replaceSelection(cur);
2807 buffer_.undo().recordUndo(cur);
2809 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2811 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2818 docstring const & BufferView::inlineCompletion() const
2820 return d->inlineCompletion_;
2824 size_t const & BufferView::inlineCompletionUniqueChars() const
2826 return d->inlineCompletionUniqueChars_;
2830 DocIterator const & BufferView::inlineCompletionPos() const
2832 return d->inlineCompletionPos_;
2836 bool samePar(DocIterator const & a, DocIterator const & b)
2838 if (a.empty() && b.empty())
2840 if (a.empty() || b.empty())
2842 if (a.depth() != b.depth())
2844 return &a.innerParagraph() == &b.innerParagraph();
2848 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2849 docstring const & completion, size_t uniqueChars)
2851 uniqueChars = min(completion.size(), uniqueChars);
2852 bool changed = d->inlineCompletion_ != completion
2853 || d->inlineCompletionUniqueChars_ != uniqueChars;
2854 bool singlePar = true;
2855 d->inlineCompletion_ = completion;
2856 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2858 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2861 DocIterator const & old = d->inlineCompletionPos_;
2863 //lyxerr << "inlineCompletionPos changed" << std::endl;
2864 // old or pos are in another paragraph?
2865 if ((!samePar(cur, pos) && !pos.empty())
2866 || (!samePar(cur, old) && !old.empty())) {
2868 //lyxerr << "different paragraph" << std::endl;
2870 d->inlineCompletionPos_ = pos;
2875 if (singlePar && !(cur.disp_.update() & Update::Force))
2876 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2878 cur.updateFlags(cur.disp_.update() | Update::Force);