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/InsetRef.h"
62 #include "insets/InsetText.h"
63 #include "insets/InsetNote.h"
65 #include "frontends/alert.h"
66 #include "frontends/Application.h"
67 #include "frontends/Delegates.h"
68 #include "frontends/FontMetrics.h"
69 #include "frontends/Painter.h"
70 #include "frontends/Selection.h"
72 #include "graphics/Previews.h"
74 #include "support/convert.h"
75 #include "support/debug.h"
76 #include "support/ExceptionMessage.h"
77 #include "support/filetools.h"
78 #include "support/gettext.h"
79 #include "support/lstrings.h"
80 #include "support/Package.h"
81 #include "support/types.h"
91 using namespace lyx::support;
95 namespace Alert = frontend::Alert;
99 /// Return an inset of this class if it exists at the current cursor position
101 T * getInsetByCode(Cursor const & cur, InsetCode code)
103 DocIterator it = cur;
104 Inset * inset = it.nextInset();
105 if (inset && inset->lyxCode() == code)
106 return static_cast<T*>(inset);
111 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
114 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
115 docstring const & contents)
117 DocIterator tmpdit = dit;
120 Inset const * inset = tmpdit.nextInset();
122 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
123 && (contents.empty() ||
124 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
128 tmpdit.forwardInset();
135 /// Looks for next inset with one of the given codes.
136 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
140 DocIterator tmpdit = dit;
141 tmpdit.forwardInset();
146 Inset const * inset = tmpdit.nextInset();
148 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
149 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
153 if (!findNextInset(tmpdit, codes, contents)) {
154 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
155 Inset * inset = &tmpdit.bottom().inset();
156 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
157 if (!findNextInset(tmpdit, codes, contents))
169 /// Looks for next inset with the given code
170 void findInset(DocIterator & dit, InsetCode code, bool same_content)
172 findInset(dit, vector<InsetCode>(1, code), same_content);
176 /// Moves cursor to the next inset with one of the given codes.
177 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
180 Cursor tmpcur = bv->cursor();
181 if (!findInset(tmpcur, codes, same_content)) {
182 bv->cursor().message(_("No more insets"));
186 tmpcur.clearSelection();
187 bv->setCursor(tmpcur);
192 /// Moves cursor to the next inset with given code.
193 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
195 gotoInset(bv, vector<InsetCode>(1, code), same_content);
199 /// A map from a Text to the associated text metrics
200 typedef map<Text const *, TextMetrics> TextMetricsCache;
202 enum ScreenUpdateStrategy {
212 /////////////////////////////////////////////////////////////////////
216 /////////////////////////////////////////////////////////////////////
218 struct BufferView::Private
220 Private(BufferView & bv): wh_(0), cursor_(bv),
221 anchor_pit_(0), anchor_ypos_(0),
222 inlineCompletionUniqueChars_(0),
223 last_inset_(0), mouse_position_cache_(),
224 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 /// 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 buffer_.updateMacros();
418 // Now do the first drawing step if needed. This consists on updating
419 // the CoordCache in updateMetrics().
420 // The second drawing step is done in WorkArea::redraw() if needed.
422 // Case when no explicit update is requested.
424 // no need to redraw anything.
425 d->update_strategy_ = NoScreenUpdate;
429 if (flags == Update::Decoration) {
430 d->update_strategy_ = DecorationUpdate;
431 buffer_.changed(false);
435 if (flags == Update::FitCursor
436 || flags == (Update::Decoration | Update::FitCursor)) {
437 // tell the frontend to update the screen if needed.
442 if (flags & Update::Decoration) {
443 d->update_strategy_ = DecorationUpdate;
444 buffer_.changed(false);
447 // no screen update is needed.
448 d->update_strategy_ = NoScreenUpdate;
452 bool const full_metrics = flags & Update::Force || !singleParUpdate();
455 // We have to update the full screen metrics.
458 if (!(flags & Update::FitCursor)) {
459 // Nothing to do anymore. Trigger a redraw and return
460 buffer_.changed(false);
464 // updateMetrics() does not update paragraph position
465 // This is done at draw() time. So we need a redraw!
466 buffer_.changed(false);
469 // The cursor is off screen so ensure it is visible.
474 updateHoveredInset();
478 void BufferView::updateScrollbar()
480 if (height_ == 0 && width_ == 0)
483 // We prefer fixed size line scrolling.
484 d->scrollbarParameters_.single_step = defaultRowHeight();
485 // We prefer full screen page scrolling.
486 d->scrollbarParameters_.page_step = height_;
488 Text & t = buffer_.text();
489 TextMetrics & tm = d->text_metrics_[&t];
491 LYXERR(Debug::GUI, " Updating scrollbar: height: "
492 << t.paragraphs().size()
493 << " curr par: " << d->cursor_.bottom().pit()
494 << " default height " << defaultRowHeight());
496 size_t const parsize = t.paragraphs().size();
497 if (d->par_height_.size() != parsize) {
498 d->par_height_.clear();
499 // FIXME: We assume a default paragraph height of 2 rows. This
500 // should probably be pondered with the screen width.
501 d->par_height_.resize(parsize, defaultRowHeight() * 2);
504 // Look at paragraph heights on-screen
505 pair<pit_type, ParagraphMetrics const *> first = tm.first();
506 pair<pit_type, ParagraphMetrics const *> last = tm.last();
507 for (pit_type pit = first.first; pit <= last.first; ++pit) {
508 d->par_height_[pit] = tm.parMetrics(pit).height();
509 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
510 << d->par_height_[pit]);
513 int top_pos = first.second->position() - first.second->ascent();
514 int bottom_pos = last.second->position() + last.second->descent();
515 bool first_visible = first.first == 0 && top_pos >= 0;
516 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
517 if (first_visible && last_visible) {
518 d->scrollbarParameters_.min = 0;
519 d->scrollbarParameters_.max = 0;
523 d->scrollbarParameters_.min = top_pos;
524 for (size_t i = 0; i != size_t(first.first); ++i)
525 d->scrollbarParameters_.min -= d->par_height_[i];
526 d->scrollbarParameters_.max = bottom_pos;
527 for (size_t i = last.first + 1; i != parsize; ++i)
528 d->scrollbarParameters_.max += d->par_height_[i];
530 d->scrollbarParameters_.position = 0;
531 // The reference is the top position so we remove one page.
532 if (lyxrc.scroll_below_document)
533 d->scrollbarParameters_.max -= minVisiblePart();
535 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
539 ScrollbarParameters const & BufferView::scrollbarParameters() const
541 return d->scrollbarParameters_;
545 docstring BufferView::toolTip(int x, int y) const
547 // Get inset under mouse, if there is one.
548 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
550 // No inset, no tooltip...
552 return covering_inset->toolTip(*this, x, y);
556 docstring BufferView::contextMenu(int x, int y) const
558 //If there is a selection, return the containing inset menu
559 if (d->cursor_.selection())
560 return d->cursor_.inset().contextMenu(*this, x, y);
562 // Get inset under mouse, if there is one.
563 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
565 return covering_inset->contextMenu(*this, x, y);
567 return buffer_.inset().contextMenu(*this, x, y);
571 void BufferView::scrollDocView(int value, bool update)
573 int const offset = value - d->scrollbarParameters_.position;
575 // No scrolling at all? No need to redraw anything
579 // If the offset is less than 2 screen height, prefer to scroll instead.
580 if (abs(offset) <= 2 * height_) {
581 d->anchor_ypos_ -= offset;
582 buffer_.changed(true);
583 updateHoveredInset();
587 // cut off at the top
588 if (value <= d->scrollbarParameters_.min) {
589 DocIterator dit = doc_iterator_begin(&buffer_);
590 showCursor(dit, false, update);
591 LYXERR(Debug::SCROLLING, "scroll to top");
595 // cut off at the bottom
596 if (value >= d->scrollbarParameters_.max) {
597 DocIterator dit = doc_iterator_end(&buffer_);
599 showCursor(dit, false, update);
600 LYXERR(Debug::SCROLLING, "scroll to bottom");
604 // find paragraph at target position
605 int par_pos = d->scrollbarParameters_.min;
607 for (; i != int(d->par_height_.size()); ++i) {
608 par_pos += d->par_height_[i];
609 if (par_pos >= value)
613 if (par_pos < value) {
614 // It seems we didn't find the correct pit so stay on the safe side and
616 LYXERR0("scrolling position not found!");
617 scrollDocView(d->scrollbarParameters_.max, update);
621 DocIterator dit = doc_iterator_begin(&buffer_);
623 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
624 showCursor(dit, false, update);
628 // FIXME: this method is not working well.
629 void BufferView::setCursorFromScrollbar()
631 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
633 int const height = 2 * defaultRowHeight();
634 int const first = height;
635 int const last = height_ - height;
637 Cursor const & oldcur = d->cursor_;
639 switch (cursorStatus(oldcur)) {
647 int const y = getPos(oldcur).y_;
648 newy = min(last, max(y, first));
652 // We reset the cursor because cursorStatus() does not
653 // work when the cursor is within mathed.
656 tm.setCursorFromCoordinates(cur, 0, newy);
658 // update the bufferview cursor and notify insets
659 // FIXME: Care about the d->cursor_ flags to redraw if needed
660 Cursor old = d->cursor_;
662 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
664 d->cursor_.fixIfBroken();
668 Change const BufferView::getCurrentChange() const
670 if (!d->cursor_.selection())
671 return Change(Change::UNCHANGED);
673 DocIterator dit = d->cursor_.selectionBegin();
674 return dit.paragraph().lookupChange(dit.pos());
678 // this could be used elsewhere as well?
679 // FIXME: This does not work within mathed!
680 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
682 Point const p = getPos(dit);
685 if (p.y_ > workHeight())
691 void BufferView::bookmarkEditPosition()
693 // Don't eat cpu time for each keystroke
694 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
697 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
701 void BufferView::saveBookmark(unsigned int idx)
703 // tentatively save bookmark, id and pos will be used to
704 // acturately locate a bookmark in a 'live' lyx session.
705 // pit and pos will be updated with bottom level pit/pos
707 if (!buffer_.isInternal()) {
708 theSession().bookmarks().save(
710 d->cursor_.bottom().pit(),
711 d->cursor_.bottom().pos(),
712 d->cursor_.paragraph().id(),
717 // emit message signal.
718 message(_("Save bookmark"));
723 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
724 int top_id, pos_type top_pos)
726 bool success = false;
729 d->cursor_.clearSelection();
731 // if a valid par_id is given, try it first
732 // This is the case for a 'live' bookmark when unique paragraph ID
733 // is used to track bookmarks.
735 dit = buffer_.getParFromID(top_id);
737 dit.pos() = min(dit.paragraph().size(), top_pos);
738 // Some slices of the iterator may not be
739 // reachable (e.g. closed collapsable inset)
740 // so the dociterator may need to be
741 // shortened. Otherwise, setCursor may crash
742 // lyx when the cursor can not be set to these
744 size_t const n = dit.depth();
745 for (size_t i = 0; i < n; ++i)
746 if (!dit[i].inset().editable()) {
754 // if top_id == 0, or searching through top_id failed
755 // This is the case for a 'restored' bookmark when only bottom
756 // (document level) pit was saved. Because of this, bookmark
757 // restoration is inaccurate. If a bookmark was within an inset,
758 // it will be restored to the left of the outmost inset that contains
760 if (bottom_pit < int(buffer_.paragraphs().size())) {
761 dit = doc_iterator_begin(&buffer_);
763 dit.pit() = bottom_pit;
764 dit.pos() = min(bottom_pos, dit.paragraph().size());
769 // Note: only bottom (document) level pit is set.
771 // set the current font.
772 d->cursor_.setCurrentFont();
773 // To center the screen on this new position we need the
774 // paragraph position which is computed at draw() time.
775 // So we need a redraw!
776 buffer_.changed(false);
785 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
787 if (lyxrc.rtl_support) {
788 if (d->cursor_.real_current_font.isRightToLeft()) {
789 if (d->intl_.keymap == Intl::PRIMARY)
790 d->intl_.keyMapSec();
792 if (d->intl_.keymap == Intl::SECONDARY)
793 d->intl_.keyMapPrim();
797 d->intl_.getTransManager().translateAndInsert(c, t, cur);
801 int BufferView::workWidth() const
807 void BufferView::recenter()
809 showCursor(d->cursor_, true, true);
813 void BufferView::showCursor()
815 showCursor(d->cursor_, false, true);
819 void BufferView::showCursor(DocIterator const & dit,
820 bool recenter, bool update)
822 if (scrollToCursor(dit, recenter) && update) {
823 buffer_.changed(true);
824 updateHoveredInset();
829 void BufferView::scrollToCursor()
831 if (scrollToCursor(d->cursor_, false)) {
832 buffer_.changed(true);
833 updateHoveredInset();
838 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
840 // We are not properly started yet, delay until resizing is
845 LYXERR(Debug::SCROLLING, "recentering!");
847 CursorSlice const & bot = dit.bottom();
848 TextMetrics & tm = d->text_metrics_[bot.text()];
850 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
851 int bot_pit = bot.pit();
852 if (bot_pit > max_pit) {
853 // FIXME: Why does this happen?
854 LYXERR0("bottom pit is greater that max pit: "
855 << bot_pit << " > " << max_pit);
859 if (bot_pit == tm.first().first - 1)
860 tm.newParMetricsUp();
861 else if (bot_pit == tm.last().first + 1)
862 tm.newParMetricsDown();
864 if (tm.contains(bot_pit)) {
865 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
866 LASSERT(!pm.rows().empty(), /**/);
867 // FIXME: smooth scrolling doesn't work in mathed.
868 CursorSlice const & cs = dit.innerTextSlice();
869 int offset = coordOffset(dit).y_;
870 int ypos = pm.position() + offset;
871 Dimension const & row_dim =
872 pm.getRow(cs.pos(), dit.boundary()).dimension();
875 scrolled = scroll(ypos - height_/2);
877 // If the top part of the row falls of the screen, we scroll
878 // up to align the top of the row with the top of the screen.
879 else if (ypos - row_dim.ascent() < 0)
880 scrolled = scrollUp(-ypos + row_dim.ascent());
882 // If the bottom of the row falls of the screen, we scroll down.
883 // However, we have to be careful not to scroll that much that
884 // the top falls of the screen.
885 else if (ypos + row_dim.descent() > height_) {
886 int ynew = height_ - row_dim.descent();
887 if (ynew < row_dim.ascent())
888 ynew = row_dim.ascent();
889 int const scroll = ypos - ynew;
890 scrolled = scrollDown(scroll);
893 // else, nothing to do, the cursor is already visible so we just return.
894 return scrolled != 0;
897 // fix inline completion position
898 if (d->inlineCompletionPos_.fixIfBroken())
899 d->inlineCompletionPos_ = DocIterator();
901 tm.redoParagraph(bot_pit);
902 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
903 int offset = coordOffset(dit).y_;
905 d->anchor_pit_ = bot_pit;
906 CursorSlice const & cs = dit.innerTextSlice();
907 Dimension const & row_dim =
908 pm.getRow(cs.pos(), dit.boundary()).dimension();
911 d->anchor_ypos_ = height_/2;
912 else if (d->anchor_pit_ == 0)
913 d->anchor_ypos_ = offset + pm.ascent();
914 else if (d->anchor_pit_ == max_pit)
915 d->anchor_ypos_ = height_ - offset - row_dim.descent();
916 else if (offset > height_)
917 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
919 d->anchor_ypos_ = defaultRowHeight() * 2;
925 void BufferView::updateDocumentClass(DocumentClass const * const olddc)
927 message(_("Converting document to new document class..."));
929 StableDocIterator backcur(d->cursor_);
930 ErrorList & el = buffer_.errorList("Class Switch");
931 cap::switchBetweenClasses(
932 olddc, buffer_.params().documentClassPtr(),
933 static_cast<InsetText &>(buffer_.inset()), el);
935 setCursor(backcur.asDocIterator(&buffer_));
937 buffer_.errors("Class Switch");
938 buffer_.updateBuffer();
941 /** Return the change status at cursor position, taking in account the
942 * status at each level of the document iterator (a table in a deleted
943 * footnote is deleted).
944 * When \param outer is true, the top slice is not looked at.
946 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
948 size_t const depth = dit.depth() - (outer ? 1 : 0);
950 for (size_t i = 0 ; i < depth ; ++i) {
951 CursorSlice const & slice = dit[i];
952 if (!slice.inset().inMathed()
953 && slice.pos() < slice.paragraph().size()) {
954 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
955 if (ch != Change::UNCHANGED)
959 return Change::UNCHANGED;
963 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
965 FuncCode const act = cmd.action();
967 // Can we use a readonly buffer?
968 if (buffer_.isReadonly()
969 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
970 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
971 flag.message(from_utf8(N_("Document is read-only")));
972 flag.setEnabled(false);
976 // Are we in a DELETED change-tracking region?
977 if (lookupChangeType(d->cursor_, true) == Change::DELETED
978 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
979 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
980 flag.message(from_utf8(N_("This portion of the document is deleted.")));
981 flag.setEnabled(false);
985 Cursor & cur = d->cursor_;
987 if (cur.getStatus(cmd, flag))
992 // FIXME: This is a bit problematic because we don't check if this is
993 // a document BufferView or not for these LFUNs. We probably have to
994 // dispatch both to currentBufferView() and, if that fails,
995 // to documentBufferView(); same as we do know for current Buffer and
996 // document Buffer. Ideally those LFUN should go to Buffer as they*
997 // operate on the full Buffer and the cursor is only needed either for
998 // an Undo record or to restore a cursor position. But we don't know
999 // how to do that inside Buffer of course.
1000 case LFUN_BUFFER_PARAMS_APPLY:
1001 case LFUN_LAYOUT_MODULES_CLEAR:
1002 case LFUN_LAYOUT_MODULE_ADD:
1003 case LFUN_LAYOUT_RELOAD:
1004 case LFUN_TEXTCLASS_APPLY:
1005 case LFUN_TEXTCLASS_LOAD:
1006 flag.setEnabled(!buffer_.isReadonly());
1010 flag.setEnabled(buffer_.undo().hasUndoStack());
1013 flag.setEnabled(buffer_.undo().hasRedoStack());
1015 case LFUN_FILE_INSERT:
1016 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1017 case LFUN_FILE_INSERT_PLAINTEXT:
1018 case LFUN_BOOKMARK_SAVE:
1019 // FIXME: Actually, these LFUNS should be moved to Text
1020 flag.setEnabled(cur.inTexted());
1023 case LFUN_FONT_STATE:
1024 case LFUN_LABEL_INSERT:
1025 case LFUN_INFO_INSERT:
1026 case LFUN_PARAGRAPH_GOTO:
1027 case LFUN_NOTE_NEXT:
1028 case LFUN_REFERENCE_NEXT:
1029 case LFUN_WORD_FIND:
1030 case LFUN_WORD_FIND_FORWARD:
1031 case LFUN_WORD_FIND_BACKWARD:
1032 case LFUN_WORD_FINDADV:
1033 case LFUN_WORD_REPLACE:
1036 case LFUN_MARK_TOGGLE:
1037 case LFUN_SCREEN_RECENTER:
1038 case LFUN_SCREEN_SHOW_CURSOR:
1039 case LFUN_BIBTEX_DATABASE_ADD:
1040 case LFUN_BIBTEX_DATABASE_DEL:
1041 case LFUN_STATISTICS:
1042 case LFUN_BRANCH_ADD_INSERT:
1043 case LFUN_KEYMAP_OFF:
1044 case LFUN_KEYMAP_PRIMARY:
1045 case LFUN_KEYMAP_SECONDARY:
1046 case LFUN_KEYMAP_TOGGLE:
1047 flag.setEnabled(true);
1050 case LFUN_LABEL_GOTO: {
1051 flag.setEnabled(!cmd.argument().empty()
1052 || getInsetByCode<InsetRef>(cur, REF_CODE));
1056 case LFUN_CHANGES_TRACK:
1057 flag.setEnabled(true);
1058 flag.setOnOff(buffer_.params().trackChanges);
1061 case LFUN_CHANGES_OUTPUT:
1062 flag.setEnabled(true);
1063 flag.setOnOff(buffer_.params().outputChanges);
1066 case LFUN_CHANGES_MERGE:
1067 case LFUN_CHANGE_NEXT:
1068 case LFUN_CHANGE_PREVIOUS:
1069 case LFUN_ALL_CHANGES_ACCEPT:
1070 case LFUN_ALL_CHANGES_REJECT:
1071 // TODO: context-sensitive enabling of LFUNs
1072 // In principle, these command should only be enabled if there
1073 // is a change in the document. However, without proper
1074 // optimizations, this will inevitably result in poor performance.
1075 flag.setEnabled(true);
1078 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1079 flag.setOnOff(buffer_.params().compressed);
1083 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
1084 flag.setOnOff(buffer_.params().output_sync);
1088 case LFUN_SCREEN_UP:
1089 case LFUN_SCREEN_DOWN:
1091 case LFUN_SCREEN_UP_SELECT:
1092 case LFUN_SCREEN_DOWN_SELECT:
1093 case LFUN_INSET_FORALL:
1094 flag.setEnabled(true);
1097 case LFUN_LAYOUT_TABULAR:
1098 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1102 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1105 case LFUN_LAYOUT_PARAGRAPH:
1106 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1109 case LFUN_DIALOG_SHOW_NEW_INSET:
1110 // FIXME: this is wrong, but I do not understand the
1112 if (cur.inset().lyxCode() == CAPTION_CODE)
1113 return cur.inset().getStatus(cur, cmd, flag);
1114 // FIXME we should consider passthru paragraphs too.
1115 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1118 case LFUN_CITATION_INSERT: {
1119 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1120 // FIXME: This could turn in a recursive hell.
1121 // Shouldn't we use Buffer::getStatus() instead?
1122 flag.setEnabled(lyx::getStatus(fr).enabled());
1125 case LFUN_INSET_APPLY: {
1126 string const name = cmd.getArg(0);
1127 Inset * inset = editedInset(name);
1129 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1130 if (!inset->getStatus(cur, fr, flag)) {
1131 // Every inset is supposed to handle this
1132 LASSERT(false, break);
1135 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1136 flag = lyx::getStatus(fr);
1149 Inset * BufferView::editedInset(string const & name) const
1151 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1152 return it == d->edited_insets_.end() ? 0 : it->second;
1156 void BufferView::editInset(string const & name, Inset * inset)
1158 d->edited_insets_[name] = inset;
1162 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1164 //lyxerr << [ cmd = " << cmd << "]" << endl;
1166 // Make sure that the cached BufferView is correct.
1167 LYXERR(Debug::ACTION, " action[" << cmd.action() << ']'
1168 << " arg[" << to_utf8(cmd.argument()) << ']'
1169 << " x[" << cmd.x() << ']'
1170 << " y[" << cmd.y() << ']'
1171 << " button[" << cmd.button() << ']');
1173 string const argument = to_utf8(cmd.argument());
1174 Cursor & cur = d->cursor_;
1176 // Don't dispatch function that does not apply to internal buffers.
1177 if (buffer_.isInternal()
1178 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1181 // We'll set this back to false if need be.
1182 bool dispatched = true;
1183 buffer_.undo().beginUndoGroup();
1185 FuncCode const act = cmd.action();
1188 case LFUN_BUFFER_PARAMS_APPLY: {
1189 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1190 cur.recordUndoFullDocument();
1191 istringstream ss(to_utf8(cmd.argument()));
1194 int const unknown_tokens = buffer_.readHeader(lex);
1195 if (unknown_tokens != 0) {
1196 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1197 << unknown_tokens << " unknown token"
1198 << (unknown_tokens == 1 ? "" : "s"));
1200 updateDocumentClass(oldClass);
1202 // We are most certainly here because of a change in the document
1203 // It is then better to make sure that all dialogs are in sync with
1204 // current document settings.
1205 dr.update(Update::Force | Update::FitCursor);
1209 case LFUN_LAYOUT_MODULES_CLEAR: {
1210 DocumentClass const * const oldClass =
1211 buffer_.params().documentClassPtr();
1212 cur.recordUndoFullDocument();
1213 buffer_.params().clearLayoutModules();
1214 buffer_.params().makeDocumentClass();
1215 updateDocumentClass(oldClass);
1216 dr.update(Update::Force | Update::FitCursor);
1220 case LFUN_LAYOUT_MODULE_ADD: {
1221 BufferParams const & params = buffer_.params();
1222 if (!params.moduleCanBeAdded(argument)) {
1223 LYXERR0("Module `" << argument <<
1224 "' cannot be added due to failed requirements or "
1225 "conflicts with installed modules.");
1228 DocumentClass const * const oldClass = params.documentClassPtr();
1229 cur.recordUndoFullDocument();
1230 buffer_.params().addLayoutModule(argument);
1231 buffer_.params().makeDocumentClass();
1232 updateDocumentClass(oldClass);
1233 dr.update(Update::Force | Update::FitCursor);
1237 case LFUN_TEXTCLASS_APPLY: {
1238 if (!LayoutFileList::get().load(argument, buffer_.temppath()) &&
1239 !LayoutFileList::get().load(argument, buffer_.filePath()))
1242 LayoutFile const * old_layout = buffer_.params().baseClass();
1243 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1245 if (old_layout == new_layout)
1249 //Save the old, possibly modular, layout for use in conversion.
1250 DocumentClass const * const oldDocClass =
1251 buffer_.params().documentClassPtr();
1252 cur.recordUndoFullDocument();
1253 buffer_.params().setBaseClass(argument);
1254 buffer_.params().makeDocumentClass();
1255 updateDocumentClass(oldDocClass);
1256 dr.update(Update::Force | Update::FitCursor);
1260 case LFUN_TEXTCLASS_LOAD:
1261 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1262 LayoutFileList::get().load(argument, buffer_.filePath());
1265 case LFUN_LAYOUT_RELOAD: {
1266 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1267 LayoutFileIndex bc = buffer_.params().baseClassID();
1268 LayoutFileList::get().reset(bc);
1269 buffer_.params().setBaseClass(bc);
1270 buffer_.params().makeDocumentClass();
1271 updateDocumentClass(oldClass);
1272 dr.update(Update::Force | Update::FitCursor);
1277 dr.setMessage(_("Undo"));
1278 cur.clearSelection();
1279 if (!cur.textUndo())
1280 dr.setMessage(_("No further undo information"));
1282 dr.update(Update::Force | Update::FitCursor);
1286 dr.setMessage(_("Redo"));
1287 cur.clearSelection();
1288 if (!cur.textRedo())
1289 dr.setMessage(_("No further redo information"));
1291 dr.update(Update::Force | Update::FitCursor);
1294 case LFUN_FONT_STATE:
1295 dr.setMessage(cur.currentState());
1298 case LFUN_BOOKMARK_SAVE:
1299 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1302 case LFUN_LABEL_GOTO: {
1303 docstring label = cmd.argument();
1304 if (label.empty()) {
1306 getInsetByCode<InsetRef>(cur, REF_CODE);
1308 label = inset->getParam("reference");
1309 // persistent=false: use temp_bookmark
1318 case LFUN_PARAGRAPH_GOTO: {
1319 int const id = convert<int>(cmd.getArg(0));
1320 int const pos = convert<int>(cmd.getArg(1));
1322 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1323 b = theBufferList().next(b)) {
1325 DocIterator dit = b->getParFromID(id);
1327 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1331 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1332 << " found in buffer `"
1333 << b->absFileName() << "'.");
1335 if (b == &buffer_) {
1339 dr.update(Update::Force | Update::FitCursor);
1341 // Switch to other buffer view and resend cmd
1342 lyx::dispatch(FuncRequest(
1343 LFUN_BUFFER_SWITCH, b->absFileName()));
1351 case LFUN_NOTE_NEXT:
1352 gotoInset(this, NOTE_CODE, false);
1355 case LFUN_REFERENCE_NEXT: {
1356 vector<InsetCode> tmp;
1357 tmp.push_back(LABEL_CODE);
1358 tmp.push_back(REF_CODE);
1359 gotoInset(this, tmp, true);
1363 case LFUN_CHANGES_TRACK:
1364 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1367 case LFUN_CHANGES_OUTPUT:
1368 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1369 if (buffer_.params().outputChanges) {
1370 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1371 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1372 LaTeXFeatures::isAvailable("xcolor");
1374 if (!dvipost && !xcolorulem) {
1375 Alert::warning(_("Changes not shown in LaTeX output"),
1376 _("Changes will not be highlighted in LaTeX output, "
1377 "because neither dvipost nor xcolor/ulem are installed.\n"
1378 "Please install these packages or redefine "
1379 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1380 } else if (!xcolorulem) {
1381 Alert::warning(_("Changes not shown in LaTeX output"),
1382 _("Changes will not be highlighted in LaTeX output "
1383 "when using pdflatex, because xcolor and ulem are not installed.\n"
1384 "Please install both packages or redefine "
1385 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1390 case LFUN_CHANGE_NEXT:
1391 findNextChange(this);
1392 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1393 dr.update(Update::Force | Update::FitCursor);
1396 case LFUN_CHANGE_PREVIOUS:
1397 findPreviousChange(this);
1398 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1399 dr.update(Update::Force | Update::FitCursor);
1402 case LFUN_CHANGES_MERGE:
1403 if (findNextChange(this) || findPreviousChange(this)) {
1404 dr.update(Update::Force | Update::FitCursor);
1405 showDialog("changes");
1409 case LFUN_ALL_CHANGES_ACCEPT:
1410 // select complete document
1412 cur.selHandle(true);
1413 buffer_.text().cursorBottom(cur);
1414 // accept everything in a single step to support atomic undo
1415 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1416 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1417 dr.update(Update::Force | Update::FitCursor);
1420 case LFUN_ALL_CHANGES_REJECT:
1421 // select complete document
1423 cur.selHandle(true);
1424 buffer_.text().cursorBottom(cur);
1425 // reject everything in a single step to support atomic undo
1426 // Note: reject does not work recursively; the user may have to repeat the operation
1427 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1428 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1429 dr.update(Update::Force | Update::FitCursor);
1432 case LFUN_WORD_FIND_FORWARD:
1433 case LFUN_WORD_FIND_BACKWARD: {
1434 static docstring last_search;
1435 docstring searched_string;
1437 if (!cmd.argument().empty()) {
1438 last_search = cmd.argument();
1439 searched_string = cmd.argument();
1441 searched_string = last_search;
1444 if (searched_string.empty())
1447 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1448 docstring const data =
1449 find2string(searched_string, true, false, fw);
1450 find(this, FuncRequest(LFUN_WORD_FIND, data));
1454 case LFUN_WORD_FIND: {
1455 FuncRequest req = cmd;
1456 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1457 req = d->search_request_cache_;
1458 if (req.argument().empty()) {
1459 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1462 if (find(this, req))
1465 message(_("String not found!"));
1466 d->search_request_cache_ = req;
1470 case LFUN_WORD_REPLACE: {
1471 bool has_deleted = false;
1472 if (cur.selection()) {
1473 DocIterator beg = cur.selectionBegin();
1474 DocIterator end = cur.selectionEnd();
1475 if (beg.pit() == end.pit()) {
1476 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1478 && cur.paragraph().isDeleted(p))
1483 replace(this, cmd, has_deleted);
1487 case LFUN_WORD_FINDADV: {
1488 FindAndReplaceOptions opt;
1489 istringstream iss(to_utf8(cmd.argument()));
1491 if (findAdv(this, opt))
1499 cur.clearSelection();
1500 dr.setMessage(from_utf8(N_("Mark off")));
1504 cur.clearSelection();
1506 dr.setMessage(from_utf8(N_("Mark on")));
1509 case LFUN_MARK_TOGGLE:
1510 cur.setSelection(false);
1513 dr.setMessage(from_utf8(N_("Mark removed")));
1516 dr.setMessage(from_utf8(N_("Mark set")));
1521 case LFUN_SCREEN_SHOW_CURSOR:
1525 case LFUN_SCREEN_RECENTER:
1529 case LFUN_BIBTEX_DATABASE_ADD: {
1530 Cursor tmpcur = cur;
1531 findInset(tmpcur, BIBTEX_CODE, false);
1532 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1535 if (inset->addDatabase(cmd.argument()))
1536 buffer_.updateBibfilesCache();
1541 case LFUN_BIBTEX_DATABASE_DEL: {
1542 Cursor tmpcur = cur;
1543 findInset(tmpcur, BIBTEX_CODE, false);
1544 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1547 if (inset->delDatabase(cmd.argument()))
1548 buffer_.updateBibfilesCache();
1553 case LFUN_STATISTICS: {
1554 DocIterator from, to;
1555 if (cur.selection()) {
1556 from = cur.selectionBegin();
1557 to = cur.selectionEnd();
1559 from = doc_iterator_begin(&buffer_);
1560 to = doc_iterator_end(&buffer_);
1562 int const words = countWords(from, to);
1563 int const chars = countChars(from, to, false);
1564 int const chars_blanks = countChars(from, to, true);
1566 if (cur.selection())
1567 message = _("Statistics for the selection:");
1569 message = _("Statistics for the document:");
1572 message += bformat(_("%1$d words"), words);
1574 message += _("One word");
1576 if (chars_blanks != 1)
1577 message += bformat(_("%1$d characters (including blanks)"),
1580 message += _("One character (including blanks)");
1583 message += bformat(_("%1$d characters (excluding blanks)"),
1586 message += _("One character (excluding blanks)");
1588 Alert::information(_("Statistics"), message);
1592 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1593 // turn compression on/off
1594 buffer_.params().compressed = !buffer_.params().compressed;
1597 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
1598 buffer_.params().output_sync = !buffer_.params().output_sync;
1601 case LFUN_SCREEN_UP:
1602 case LFUN_SCREEN_DOWN: {
1603 Point p = getPos(cur);
1604 // This code has been commented out to enable to scroll down a
1605 // document, even if there are large insets in it (see bug #5465).
1606 /*if (p.y_ < 0 || p.y_ > height_) {
1607 // The cursor is off-screen so recenter before proceeding.
1611 int const scrolled = scroll(act == LFUN_SCREEN_UP
1612 ? -height_ : height_);
1613 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1615 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1616 p = Point(width_, height_);
1618 bool const in_texted = cur.inTexted();
1620 buffer_.changed(true);
1621 updateHoveredInset();
1623 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1624 true, act == LFUN_SCREEN_UP);
1625 //FIXME: what to do with cur.x_target()?
1626 bool update = in_texted && cur.bv().checkDepm(cur, old);
1629 dr.update(Update::Force | Update::FitCursor);
1637 case LFUN_SCREEN_UP_SELECT: {
1638 cur.selHandle(true);
1639 if (isTopScreen()) {
1640 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1644 int y = getPos(cur).y_;
1645 int const ymin = y - height_ + defaultRowHeight();
1646 while (y > ymin && cur.up())
1650 dr.update(Update::SinglePar | Update::FitCursor);
1654 case LFUN_SCREEN_DOWN_SELECT: {
1655 cur.selHandle(true);
1656 if (isBottomScreen()) {
1657 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1661 int y = getPos(cur).y_;
1662 int const ymax = y + height_ - defaultRowHeight();
1663 while (y < ymax && cur.down())
1667 dr.update(Update::SinglePar | Update::FitCursor);
1672 // This would be in Buffer class if only Cursor did not
1673 // require a bufferview
1674 case LFUN_INSET_FORALL: {
1675 docstring const name = from_utf8(cmd.getArg(0));
1676 string const commandstr = cmd.getLongArg(1);
1677 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1679 // an arbitrary number to limit number of iterations
1680 const int max_iter = 10000;
1682 Cursor & cur = d->cursor_;
1683 Cursor const savecur = cur;
1685 if (!cur.nextInset())
1687 cur.beginUndoGroup();
1688 while(cur && iterations < max_iter) {
1689 Inset * ins = cur.nextInset();
1692 docstring insname = ins->name();
1693 while (!insname.empty()) {
1694 if (insname == name || name == from_utf8("*")) {
1696 lyx::dispatch(fr, dr);
1700 size_t const i = insname.rfind(':');
1701 if (i == string::npos)
1703 insname = insname.substr(0, i);
1710 dr.update(Update::Force);
1712 if (iterations >= max_iter) {
1714 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1716 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1721 case LFUN_BRANCH_ADD_INSERT: {
1722 docstring branch_name = from_utf8(cmd.getArg(0));
1723 if (branch_name.empty())
1724 if (!Alert::askForText(branch_name, _("Branch name")) ||
1725 branch_name.empty())
1728 DispatchResult drtmp;
1729 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1730 if (drtmp.error()) {
1731 Alert::warning(_("Branch already exists"), drtmp.message());
1734 BranchList & branch_list = buffer_.params().branchlist();
1735 vector<docstring> const branches =
1736 getVectorFromString(branch_name, branch_list.separator());
1737 for (vector<docstring>::const_iterator it = branches.begin();
1738 it != branches.end(); ++it) {
1740 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1745 case LFUN_KEYMAP_OFF:
1746 getIntl().keyMapOn(false);
1749 case LFUN_KEYMAP_PRIMARY:
1750 getIntl().keyMapPrim();
1753 case LFUN_KEYMAP_SECONDARY:
1754 getIntl().keyMapSec();
1757 case LFUN_KEYMAP_TOGGLE:
1758 getIntl().toggleKeyMap();
1761 case LFUN_DIALOG_SHOW_NEW_INSET: {
1762 string const name = cmd.getArg(0);
1763 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1764 if (decodeInsetParam(name, data, buffer_))
1765 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1767 lyxerr << "Inset type '" << name <<
1768 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1772 case LFUN_CITATION_INSERT: {
1773 if (argument.empty()) {
1774 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1777 // we can have one optional argument, delimited by '|'
1778 // citation-insert <key>|<text_before>
1779 // this should be enhanced to also support text_after
1780 // and citation style
1781 string arg = argument;
1783 if (contains(argument, "|")) {
1784 arg = token(argument, '|', 0);
1785 opt1 = token(argument, '|', 1);
1787 InsetCommandParams icp(CITE_CODE);
1788 icp["key"] = from_utf8(arg);
1790 icp["before"] = from_utf8(opt1);
1791 string icstr = InsetCommand::params2string("citation", icp);
1792 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1797 case LFUN_INSET_APPLY: {
1798 string const name = cmd.getArg(0);
1799 Inset * inset = editedInset(name);
1801 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1805 // put cursor in front of inset.
1806 if (!setCursorFromInset(inset)) {
1807 LASSERT(false, break);
1810 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1811 inset->dispatch(cur, fr);
1812 dr.update(Update::SinglePar | Update::FitCursor);
1821 buffer_.undo().endUndoGroup();
1822 dr.dispatched(dispatched);
1827 docstring const BufferView::requestSelection()
1829 Cursor & cur = d->cursor_;
1831 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1832 if (!cur.selection()) {
1833 d->xsel_cache_.set = false;
1837 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1838 if (!d->xsel_cache_.set ||
1839 cur.top() != d->xsel_cache_.cursor ||
1840 cur.realAnchor().top() != d->xsel_cache_.anchor)
1842 d->xsel_cache_.cursor = cur.top();
1843 d->xsel_cache_.anchor = cur.realAnchor().top();
1844 d->xsel_cache_.set = cur.selection();
1845 return cur.selectionAsString(false);
1851 void BufferView::clearSelection()
1853 d->cursor_.clearSelection();
1854 // Clear the selection buffer. Otherwise a subsequent
1855 // middle-mouse-button paste would use the selection buffer,
1856 // not the more current external selection.
1857 cap::clearSelection();
1858 d->xsel_cache_.set = false;
1859 // The buffer did not really change, but this causes the
1860 // redraw we need because we cleared the selection above.
1861 buffer_.changed(false);
1865 void BufferView::resize(int width, int height)
1867 // Update from work area
1871 // Clear the paragraph height cache.
1872 d->par_height_.clear();
1873 // Redo the metrics.
1878 Inset const * BufferView::getCoveringInset(Text const & text,
1881 TextMetrics & tm = d->text_metrics_[&text];
1882 Inset * inset = tm.checkInsetHit(x, y);
1886 if (!inset->descendable(*this))
1887 // No need to go further down if the inset is not
1891 size_t cell_number = inset->nargs();
1892 // Check all the inner cell.
1893 for (size_t i = 0; i != cell_number; ++i) {
1894 Text const * inner_text = inset->getText(i);
1897 Inset const * inset_deeper =
1898 getCoveringInset(*inner_text, x, y);
1900 return inset_deeper;
1908 void BufferView::updateHoveredInset() const
1910 // Get inset under mouse, if there is one.
1911 Inset const * covering_inset = getCoveringInset(buffer_.text(),
1912 d->mouse_position_cache_.x_, d->mouse_position_cache_.y_);
1913 if (covering_inset == d->last_inset_)
1914 // Same inset, no need to do anything...
1917 bool need_redraw = false;
1918 if (d->last_inset_) {
1919 // Remove the hint on the last hovered inset (if any).
1920 need_redraw |= d->last_inset_->setMouseHover(this, false);
1924 // const_cast because of setMouseHover().
1925 Inset * inset = const_cast<Inset *>(covering_inset);
1926 if (inset && inset->setMouseHover(this, true)) {
1928 // Only the insets that accept the hover state, do
1929 // clear the last_inset_, so only set the last_inset_
1930 // member if the hovered setting is accepted.
1931 d->last_inset_ = inset;
1935 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1936 << d->mouse_position_cache_.x_ << ", "
1937 << d->mouse_position_cache_.y_ << ")");
1939 d->update_strategy_ = DecorationUpdate;
1941 // This event (moving without mouse click) is not passed further.
1942 // This should be changed if it is further utilized.
1943 buffer_.changed(false);
1948 void BufferView::clearLastInset(Inset * inset) const
1950 if (d->last_inset_ != inset) {
1951 LYXERR0("Wrong last_inset!");
1952 LASSERT(false, /**/);
1958 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1960 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1962 // This is only called for mouse related events including
1963 // LFUN_FILE_OPEN generated by drag-and-drop.
1964 FuncRequest cmd = cmd0;
1966 Cursor old = cursor();
1968 cur.push(buffer_.inset());
1969 cur.setSelection(d->cursor_.selection());
1971 // Either the inset under the cursor or the
1972 // surrounding Text will handle this event.
1974 // make sure we stay within the screen...
1975 cmd.set_y(min(max(cmd.y(), -1), height_));
1977 d->mouse_position_cache_.x_ = cmd.x();
1978 d->mouse_position_cache_.y_ = cmd.y();
1980 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1981 updateHoveredInset();
1985 // Build temporary cursor.
1986 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
1988 // Put anchor at the same position.
1991 cur.beginUndoGroup();
1993 // Try to dispatch to an non-editable inset near this position
1994 // via the temp cursor. If the inset wishes to change the real
1995 // cursor it has to do so explicitly by using
1996 // cur.bv().cursor() = cur; (or similar)
1998 inset->dispatch(cur, cmd);
2000 // Now dispatch to the temporary cursor. If the real cursor should
2001 // be modified, the inset's dispatch has to do so explicitly.
2002 if (!inset || !cur.result().dispatched())
2007 // Notify left insets
2010 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2012 cursor().fixIfBroken();
2015 // Do we have a selection?
2016 theSelection().haveSelection(cursor().selection());
2018 // If the command has been dispatched,
2019 if (cur.result().dispatched() || cur.result().update())
2020 processUpdateFlags(cur.result().update());
2024 void BufferView::lfunScroll(FuncRequest const & cmd)
2026 string const scroll_type = cmd.getArg(0);
2027 int scroll_step = 0;
2028 if (scroll_type == "line")
2029 scroll_step = d->scrollbarParameters_.single_step;
2030 else if (scroll_type == "page")
2031 scroll_step = d->scrollbarParameters_.page_step;
2034 string const scroll_quantity = cmd.getArg(1);
2035 if (scroll_quantity == "up")
2036 scrollUp(scroll_step);
2037 else if (scroll_quantity == "down")
2038 scrollDown(scroll_step);
2040 int const scroll_value = convert<int>(scroll_quantity);
2042 scroll(scroll_step * scroll_value);
2044 buffer_.changed(true);
2045 updateHoveredInset();
2049 int BufferView::minVisiblePart()
2051 return 2 * defaultRowHeight();
2055 int BufferView::scroll(int y)
2058 return scrollDown(y);
2060 return scrollUp(-y);
2065 int BufferView::scrollDown(int offset)
2067 Text * text = &buffer_.text();
2068 TextMetrics & tm = d->text_metrics_[text];
2069 int const ymax = height_ + offset;
2071 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2072 int bottom_pos = last.second->position() + last.second->descent();
2073 if (lyxrc.scroll_below_document)
2074 bottom_pos += height_ - minVisiblePart();
2075 if (last.first + 1 == int(text->paragraphs().size())) {
2076 if (bottom_pos <= height_)
2078 offset = min(offset, bottom_pos - height_);
2081 if (bottom_pos > ymax)
2083 tm.newParMetricsDown();
2085 d->anchor_ypos_ -= offset;
2090 int BufferView::scrollUp(int offset)
2092 Text * text = &buffer_.text();
2093 TextMetrics & tm = d->text_metrics_[text];
2094 int ymin = - offset;
2096 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2097 int top_pos = first.second->position() - first.second->ascent();
2098 if (first.first == 0) {
2101 offset = min(offset, - top_pos);
2106 tm.newParMetricsUp();
2108 d->anchor_ypos_ += offset;
2113 void BufferView::setCursorFromRow(int row)
2118 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2122 buffer_.text().setCursor(d->cursor_, 0, 0);
2124 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
2129 bool BufferView::setCursorFromInset(Inset const * inset)
2131 // are we already there?
2132 if (cursor().nextInset() == inset)
2135 // Inset is not at cursor position. Find it in the document.
2138 while (cur && cur.nextInset() != inset)
2149 void BufferView::gotoLabel(docstring const & label)
2151 std::vector<Buffer const *> bufs = buffer().allRelatives();
2152 std::vector<Buffer const *>::iterator it = bufs.begin();
2153 for (; it != bufs.end(); ++it) {
2154 Buffer const * buf = *it;
2157 Toc & toc = buf->tocBackend().toc("label");
2158 TocIterator toc_it = toc.begin();
2159 TocIterator end = toc.end();
2160 for (; toc_it != end; ++toc_it) {
2161 if (label == toc_it->str()) {
2162 lyx::dispatch(toc_it->action());
2170 TextMetrics const & BufferView::textMetrics(Text const * t) const
2172 return const_cast<BufferView *>(this)->textMetrics(t);
2176 TextMetrics & BufferView::textMetrics(Text const * t)
2178 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2179 if (tmc_it == d->text_metrics_.end()) {
2180 tmc_it = d->text_metrics_.insert(
2181 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2183 return tmc_it->second;
2187 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2190 return textMetrics(t).parMetrics(pit);
2194 int BufferView::workHeight() const
2200 void BufferView::setCursor(DocIterator const & dit)
2203 size_t const n = dit.depth();
2204 for (size_t i = 0; i < n; ++i)
2205 dit[i].inset().edit(d->cursor_, true);
2207 d->cursor_.setCursor(dit);
2208 d->cursor_.setSelection(false);
2212 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2214 // Would be wrong to delete anything if we have a selection.
2215 if (cur.selection())
2218 bool need_anchor_change = false;
2219 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2220 need_anchor_change);
2222 if (need_anchor_change)
2230 buffer_.updateBuffer();
2231 buffer_.changed(true);
2236 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2238 LASSERT(&cur.bv() == this, /**/);
2241 // this event will clear selection so we save selection for
2242 // persistent selection
2243 cap::saveSelection(cursor());
2245 d->cursor_.macroModeClose();
2247 // Has the cursor just left the inset?
2248 bool leftinset = (&d->cursor_.inset() != &cur.inset());
2250 d->cursor_.fixIfBroken();
2252 // FIXME: shift-mouse selection doesn't work well across insets.
2253 bool do_selection = select && &d->cursor_.normalAnchor().inset() == &cur.inset();
2255 // do the dEPM magic if needed
2256 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2257 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2258 // the leftinset bool would not be necessary (badcursor instead).
2259 bool update = leftinset;
2260 if (!do_selection && d->cursor_.inTexted())
2261 update |= checkDepm(cur, d->cursor_);
2264 d->cursor_.resetAnchor();
2265 d->cursor_.setCursor(cur);
2266 d->cursor_.boundary(cur.boundary());
2268 d->cursor_.setSelection();
2270 d->cursor_.clearSelection();
2272 d->cursor_.finishUndo();
2273 d->cursor_.setCurrentFont();
2278 void BufferView::putSelectionAt(DocIterator const & cur,
2279 int length, bool backwards)
2281 d->cursor_.clearSelection();
2287 d->cursor_.pos() += length;
2288 d->cursor_.setSelection(d->cursor_, -length);
2290 d->cursor_.setSelection(d->cursor_, length);
2292 // Ensure a redraw happens in any case because the new selection could
2293 // possibly be on the same screen as the previous selection.
2294 processUpdateFlags(Update::Force | Update::FitCursor);
2298 Cursor & BufferView::cursor()
2304 Cursor const & BufferView::cursor() const
2310 pit_type BufferView::anchor_ref() const
2312 return d->anchor_pit_;
2316 bool BufferView::singleParUpdate()
2318 Text & buftext = buffer_.text();
2319 pit_type const bottom_pit = d->cursor_.bottom().pit();
2320 TextMetrics & tm = textMetrics(&buftext);
2321 int old_height = tm.parMetrics(bottom_pit).height();
2323 // make sure inline completion pointer is ok
2324 if (d->inlineCompletionPos_.fixIfBroken())
2325 d->inlineCompletionPos_ = DocIterator();
2327 // In Single Paragraph mode, rebreak only
2328 // the (main text, not inset!) paragraph containing the cursor.
2329 // (if this paragraph contains insets etc., rebreaking will
2330 // recursively descend)
2331 tm.redoParagraph(bottom_pit);
2332 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2333 if (pm.height() != old_height)
2334 // Paragraph height has changed so we cannot proceed to
2335 // the singlePar optimisation.
2338 d->update_strategy_ = SingleParUpdate;
2340 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2341 << " y2: " << pm.position() + pm.descent()
2342 << " pit: " << bottom_pit
2343 << " singlepar: 1");
2348 void BufferView::updateMetrics()
2350 if (height_ == 0 || width_ == 0)
2353 Text & buftext = buffer_.text();
2354 pit_type const npit = int(buftext.paragraphs().size());
2356 // Clear out the position cache in case of full screen redraw,
2357 d->coord_cache_.clear();
2359 // Clear out paragraph metrics to avoid having invalid metrics
2360 // in the cache from paragraphs not relayouted below
2361 // The complete text metrics will be redone.
2362 d->text_metrics_.clear();
2364 TextMetrics & tm = textMetrics(&buftext);
2366 // make sure inline completion pointer is ok
2367 if (d->inlineCompletionPos_.fixIfBroken())
2368 d->inlineCompletionPos_ = DocIterator();
2370 if (d->anchor_pit_ >= npit)
2371 // The anchor pit must have been deleted...
2372 d->anchor_pit_ = npit - 1;
2374 // Rebreak anchor paragraph.
2375 tm.redoParagraph(d->anchor_pit_);
2376 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2379 if (d->anchor_pit_ == 0) {
2380 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2382 // Complete buffer visible? Then it's easy.
2383 if (scrollRange == 0)
2384 d->anchor_ypos_ = anchor_pm.ascent();
2386 // FIXME: Some clever handling needed to show
2387 // the _first_ paragraph up to the top if the cursor is
2388 // in the first line.
2390 anchor_pm.setPosition(d->anchor_ypos_);
2392 LYXERR(Debug::PAINTING, "metrics: "
2393 << " anchor pit = " << d->anchor_pit_
2394 << " anchor ypos = " << d->anchor_ypos_);
2396 // Redo paragraphs above anchor if necessary.
2397 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2398 // We are now just above the anchor paragraph.
2399 pit_type pit1 = d->anchor_pit_ - 1;
2400 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2401 tm.redoParagraph(pit1);
2402 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2404 // Save the paragraph position in the cache.
2409 // Redo paragraphs below the anchor if necessary.
2410 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2411 // We are now just below the anchor paragraph.
2412 pit_type pit2 = d->anchor_pit_ + 1;
2413 for (; pit2 < npit && y2 <= height_; ++pit2) {
2414 tm.redoParagraph(pit2);
2415 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2417 // Save the paragraph position in the cache.
2422 LYXERR(Debug::PAINTING, "Metrics: "
2423 << " anchor pit = " << d->anchor_pit_
2424 << " anchor ypos = " << d->anchor_ypos_
2427 << " pit1 = " << pit1
2428 << " pit2 = " << pit2);
2430 d->update_strategy_ = FullScreenUpdate;
2432 if (lyxerr.debugging(Debug::WORKAREA)) {
2433 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2434 d->coord_cache_.dump();
2439 void BufferView::insertLyXFile(FileName const & fname)
2441 LASSERT(d->cursor_.inTexted(), /**/);
2443 // Get absolute path of file and add ".lyx"
2444 // to the filename if necessary
2445 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2447 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2448 // emit message signal.
2449 message(bformat(_("Inserting document %1$s..."), disp_fn));
2452 Buffer buf("", false);
2453 if (buf.loadLyXFile(filename)) {
2454 ErrorList & el = buffer_.errorList("Parse");
2455 // Copy the inserted document error list into the current buffer one.
2456 el = buf.errorList("Parse");
2457 buffer_.undo().recordUndo(d->cursor_);
2458 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2459 buf.params().documentClassPtr(), el);
2460 res = _("Document %1$s inserted.");
2462 res = _("Could not insert document %1$s");
2465 buffer_.changed(true);
2466 // emit message signal.
2467 message(bformat(res, disp_fn));
2468 buffer_.errors("Parse");
2472 Point BufferView::coordOffset(DocIterator const & dit) const
2478 // Addup contribution of nested insets, from inside to outside,
2479 // keeping the outer paragraph for a special handling below
2480 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2481 CursorSlice const & sl = dit[i];
2485 // get relative position inside sl.inset()
2486 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2488 // Make relative position inside of the edited inset relative to sl.inset()
2492 // In case of an RTL inset, the edited inset will be positioned to the left
2495 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2496 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2501 // remember width for the case that sl.inset() is positioned in an RTL inset
2502 if (i && dit[i - 1].text()) {
2503 // If this Inset is inside a Text Inset, retrieve the Dimension
2504 // from the containing text instead of using Inset::dimension() which
2505 // might not be implemented.
2506 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2507 // elimination of Inset::dim_ cache. This coordOffset() method needs
2508 // to be rewritten in light of the new design.
2509 Dimension const & dim = parMetrics(dit[i - 1].text(),
2510 dit[i - 1].pit()).insetDimension(&sl.inset());
2513 Dimension const dim = sl.inset().dimension(*this);
2517 //lyxerr << "Cursor::getPos, i: "
2518 // << i << " x: " << xx << " y: " << y << endl;
2521 // Add contribution of initial rows of outermost paragraph
2522 CursorSlice const & sl = dit[0];
2523 TextMetrics const & tm = textMetrics(sl.text());
2524 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2525 LASSERT(!pm.rows().empty(), /**/);
2526 y -= pm.rows()[0].ascent();
2528 // FIXME: document this mess
2530 if (sl.pos() > 0 && dit.depth() == 1) {
2532 if (pos && dit.boundary())
2534 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2535 rend = pm.pos2row(pos);
2537 rend = pm.pos2row(sl.pos());
2539 size_t rend = pm.pos2row(sl.pos());
2541 for (size_t rit = 0; rit != rend; ++rit)
2542 y += pm.rows()[rit].height();
2543 y += pm.rows()[rend].ascent();
2545 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2547 // Make relative position from the nested inset now bufferview absolute.
2548 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2551 // In the RTL case place the nested inset at the left of the cursor in
2552 // the outer paragraph
2553 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2554 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2562 Point BufferView::getPos(DocIterator const & dit) const
2564 if (!paragraphVisible(dit))
2565 return Point(-1, -1);
2567 CursorSlice const & bot = dit.bottom();
2568 TextMetrics const & tm = textMetrics(bot.text());
2570 // offset from outer paragraph
2571 Point p = coordOffset(dit);
2572 p.y_ += tm.parMetrics(bot.pit()).position();
2577 bool BufferView::paragraphVisible(DocIterator const & dit) const
2579 CursorSlice const & bot = dit.bottom();
2580 TextMetrics const & tm = textMetrics(bot.text());
2582 return tm.contains(bot.pit());
2586 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2588 Cursor const & cur = cursor();
2589 Font const font = cur.getFont();
2590 frontend::FontMetrics const & fm = theFontMetrics(font);
2591 int const asc = fm.maxAscent();
2592 int const des = fm.maxDescent();
2599 bool BufferView::cursorInView(Point const & p, int h) const
2601 Cursor const & cur = cursor();
2602 // does the cursor touch the screen ?
2603 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2609 void BufferView::draw(frontend::Painter & pain)
2611 if (height_ == 0 || width_ == 0)
2613 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2615 Text & text = buffer_.text();
2616 TextMetrics const & tm = d->text_metrics_[&text];
2617 int const y = tm.first().second->position();
2618 PainterInfo pi(this, pain);
2620 switch (d->update_strategy_) {
2622 case NoScreenUpdate:
2623 // If no screen painting is actually needed, only some the different
2624 // coordinates of insets and paragraphs needs to be updated.
2625 pi.full_repaint = true;
2626 pi.pain.setDrawingEnabled(false);
2630 case SingleParUpdate:
2631 pi.full_repaint = false;
2632 // In general, only the current row of the outermost paragraph
2633 // will be redrawn. Particular cases where selection spans
2634 // multiple paragraph are correctly detected in TextMetrics.
2638 case DecorationUpdate:
2639 // FIXME: We should also distinguish DecorationUpdate to avoid text
2640 // drawing if possible. This is not possible to do easily right now
2641 // because of the single backing pixmap.
2643 case FullScreenUpdate:
2644 // The whole screen, including insets, will be refreshed.
2645 pi.full_repaint = true;
2647 // Clear background.
2648 pain.fillRectangle(0, 0, width_, height_,
2649 pi.backgroundColor(&buffer_.inset()));
2654 // and possibly grey out below
2655 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2656 int const y2 = lastpm.second->position() + lastpm.second->descent();
2659 Color color = buffer().isInternal()
2660 ? Color_background : Color_bottomarea;
2661 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2665 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2667 // The scrollbar needs an update.
2670 // Normalize anchor for next time
2671 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2672 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2673 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2674 ParagraphMetrics const & pm = tm.parMetrics(pit);
2675 if (pm.position() + pm.descent() > 0) {
2676 d->anchor_pit_ = pit;
2677 d->anchor_ypos_ = pm.position();
2681 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2682 << " anchor ypos = " << d->anchor_ypos_);
2686 void BufferView::message(docstring const & msg)
2689 d->gui_->message(msg);
2693 void BufferView::showDialog(string const & name)
2696 d->gui_->showDialog(name, string());
2700 void BufferView::showDialog(string const & name,
2701 string const & data, Inset * inset)
2704 d->gui_->showDialog(name, data, inset);
2708 void BufferView::updateDialog(string const & name, string const & data)
2711 d->gui_->updateDialog(name, data);
2715 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2721 // FIXME: Move this out of BufferView again
2722 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2724 if (!fname.isReadableFile()) {
2725 docstring const error = from_ascii(strerror(errno));
2726 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2727 docstring const text =
2728 bformat(_("Could not read the specified document\n"
2729 "%1$s\ndue to the error: %2$s"), file, error);
2730 Alert::error(_("Could not read file"), text);
2734 if (!fname.isReadableFile()) {
2735 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2736 docstring const text =
2737 bformat(_("%1$s\n is not readable."), file);
2738 Alert::error(_("Could not open file"), text);
2742 // FIXME UNICODE: We don't know the encoding of the file
2743 docstring file_content = fname.fileContents("UTF-8");
2744 if (file_content.empty()) {
2745 Alert::error(_("Reading not UTF-8 encoded file"),
2746 _("The file is not UTF-8 encoded.\n"
2747 "It will be read as local 8Bit-encoded.\n"
2748 "If this does not give the correct result\n"
2749 "then please change the encoding of the file\n"
2750 "to UTF-8 with a program other than LyX.\n"));
2751 file_content = fname.fileContents("local8bit");
2754 return normalize_c(file_content);
2758 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2760 docstring const tmpstr = contentsOfPlaintextFile(f);
2765 Cursor & cur = cursor();
2766 cap::replaceSelection(cur);
2767 buffer_.undo().recordUndo(cur);
2769 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2771 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2773 buffer_.changed(true);
2777 docstring const & BufferView::inlineCompletion() const
2779 return d->inlineCompletion_;
2783 size_t const & BufferView::inlineCompletionUniqueChars() const
2785 return d->inlineCompletionUniqueChars_;
2789 DocIterator const & BufferView::inlineCompletionPos() const
2791 return d->inlineCompletionPos_;
2795 bool samePar(DocIterator const & a, DocIterator const & b)
2797 if (a.empty() && b.empty())
2799 if (a.empty() || b.empty())
2801 if (a.depth() != b.depth())
2803 return &a.innerParagraph() == &b.innerParagraph();
2807 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2808 docstring const & completion, size_t uniqueChars)
2810 uniqueChars = min(completion.size(), uniqueChars);
2811 bool changed = d->inlineCompletion_ != completion
2812 || d->inlineCompletionUniqueChars_ != uniqueChars;
2813 bool singlePar = true;
2814 d->inlineCompletion_ = completion;
2815 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2817 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2820 DocIterator const & old = d->inlineCompletionPos_;
2822 //lyxerr << "inlineCompletionPos changed" << std::endl;
2823 // old or pos are in another paragraph?
2824 if ((!samePar(cur, pos) && !pos.empty())
2825 || (!samePar(cur, old) && !old.empty())) {
2827 //lyxerr << "different paragraph" << std::endl;
2829 d->inlineCompletionPos_ = pos;
2834 if (singlePar && !(cur.result().update() & Update::Force))
2835 cur.updateFlags(cur.result().update() | Update::SinglePar);
2837 cur.updateFlags(cur.result().update() | Update::Force);