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);
323 int BufferView::rightMargin() const
325 // The additional test for the case the outliner is opened.
327 !lyxrc.full_screen_limit ||
328 width_ < lyxrc.full_screen_width + 20)
331 return (width_ - lyxrc.full_screen_width) / 2;
335 int BufferView::leftMargin() const
337 return rightMargin();
341 bool BufferView::isTopScreen() const
343 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
347 bool BufferView::isBottomScreen() const
349 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
353 Intl & BufferView::getIntl()
359 Intl const & BufferView::getIntl() const
365 CoordCache & BufferView::coordCache()
367 return d->coord_cache_;
371 CoordCache const & BufferView::coordCache() const
373 return d->coord_cache_;
377 Buffer & BufferView::buffer()
383 Buffer const & BufferView::buffer() const
389 bool BufferView::fitCursor()
391 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
392 frontend::FontMetrics const & fm =
393 theFontMetrics(d->cursor_.getFont().fontInfo());
394 int const asc = fm.maxAscent();
395 int const des = fm.maxDescent();
396 Point const p = getPos(d->cursor_, d->cursor_.boundary());
397 if (p.y_ - asc >= 0 && p.y_ + des < height_)
404 void BufferView::processUpdateFlags(Update::flags flags)
406 // This is close to a hot-path.
407 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
408 << "[fitcursor = " << (flags & Update::FitCursor)
409 << ", forceupdate = " << (flags & Update::Force)
410 << ", singlepar = " << (flags & Update::SinglePar)
411 << "] buffer: " << &buffer_);
413 buffer_.updateMacros();
415 // Now do the first drawing step if needed. This consists on updating
416 // the CoordCache in updateMetrics().
417 // The second drawing step is done in WorkArea::redraw() if needed.
419 // Case when no explicit update is requested.
421 // no need to redraw anything.
422 d->update_strategy_ = NoScreenUpdate;
426 if (flags == Update::Decoration) {
427 d->update_strategy_ = DecorationUpdate;
428 buffer_.changed(false);
432 if (flags == Update::FitCursor
433 || flags == (Update::Decoration | Update::FitCursor)) {
434 // tell the frontend to update the screen if needed.
439 if (flags & Update::Decoration) {
440 d->update_strategy_ = DecorationUpdate;
441 buffer_.changed(false);
444 // no screen update is needed.
445 d->update_strategy_ = NoScreenUpdate;
449 bool const full_metrics = flags & Update::Force || !singleParUpdate();
452 // We have to update the full screen metrics.
455 if (!(flags & Update::FitCursor)) {
456 // Nothing to do anymore. Trigger a redraw and return
457 buffer_.changed(false);
461 // updateMetrics() does not update paragraph position
462 // This is done at draw() time. So we need a redraw!
463 buffer_.changed(false);
466 // The cursor is off screen so ensure it is visible.
471 updateHoveredInset();
475 void BufferView::updateScrollbar()
477 if (height_ == 0 && width_ == 0)
480 // We prefer fixed size line scrolling.
481 d->scrollbarParameters_.single_step = defaultRowHeight();
482 // We prefer full screen page scrolling.
483 d->scrollbarParameters_.page_step = height_;
485 Text & t = buffer_.text();
486 TextMetrics & tm = d->text_metrics_[&t];
488 LYXERR(Debug::GUI, " Updating scrollbar: height: "
489 << t.paragraphs().size()
490 << " curr par: " << d->cursor_.bottom().pit()
491 << " default height " << defaultRowHeight());
493 size_t const parsize = t.paragraphs().size();
494 if (d->par_height_.size() != parsize) {
495 d->par_height_.clear();
496 // FIXME: We assume a default paragraph height of 2 rows. This
497 // should probably be pondered with the screen width.
498 d->par_height_.resize(parsize, defaultRowHeight() * 2);
501 // Look at paragraph heights on-screen
502 pair<pit_type, ParagraphMetrics const *> first = tm.first();
503 pair<pit_type, ParagraphMetrics const *> last = tm.last();
504 for (pit_type pit = first.first; pit <= last.first; ++pit) {
505 d->par_height_[pit] = tm.parMetrics(pit).height();
506 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
507 << d->par_height_[pit]);
510 int top_pos = first.second->position() - first.second->ascent();
511 int bottom_pos = last.second->position() + last.second->descent();
512 bool first_visible = first.first == 0 && top_pos >= 0;
513 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
514 if (first_visible && last_visible) {
515 d->scrollbarParameters_.min = 0;
516 d->scrollbarParameters_.max = 0;
520 d->scrollbarParameters_.min = top_pos;
521 for (size_t i = 0; i != size_t(first.first); ++i)
522 d->scrollbarParameters_.min -= d->par_height_[i];
523 d->scrollbarParameters_.max = bottom_pos;
524 for (size_t i = last.first + 1; i != parsize; ++i)
525 d->scrollbarParameters_.max += d->par_height_[i];
527 d->scrollbarParameters_.position = 0;
528 // The reference is the top position so we remove one page.
529 if (lyxrc.scroll_below_document)
530 d->scrollbarParameters_.max -= minVisiblePart();
532 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
536 ScrollbarParameters const & BufferView::scrollbarParameters() const
538 return d->scrollbarParameters_;
542 docstring BufferView::toolTip(int x, int y) const
544 // Get inset under mouse, if there is one.
545 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
547 // No inset, no tooltip...
549 return covering_inset->toolTip(*this, x, y);
553 docstring BufferView::contextMenu(int x, int y) const
555 //If there is a selection, return the containing inset menu
556 if (d->cursor_.selection())
557 return d->cursor_.inset().contextMenu(*this, x, y);
559 // Get inset under mouse, if there is one.
560 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
562 return covering_inset->contextMenu(*this, x, y);
564 return buffer_.inset().contextMenu(*this, x, y);
568 void BufferView::scrollDocView(int value)
570 int const offset = value - d->scrollbarParameters_.position;
572 // No scrolling at all? No need to redraw anything
576 // If the offset is less than 2 screen height, prefer to scroll instead.
577 if (abs(offset) <= 2 * height_) {
578 d->anchor_ypos_ -= offset;
579 buffer_.changed(true);
580 updateHoveredInset();
584 // cut off at the top
585 if (value <= d->scrollbarParameters_.min) {
586 DocIterator dit = doc_iterator_begin(&buffer_);
588 LYXERR(Debug::SCROLLING, "scroll to top");
592 // cut off at the bottom
593 if (value >= d->scrollbarParameters_.max) {
594 DocIterator dit = doc_iterator_end(&buffer_);
597 LYXERR(Debug::SCROLLING, "scroll to bottom");
601 // find paragraph at target position
602 int par_pos = d->scrollbarParameters_.min;
604 for (; i != int(d->par_height_.size()); ++i) {
605 par_pos += d->par_height_[i];
606 if (par_pos >= value)
610 if (par_pos < value) {
611 // It seems we didn't find the correct pit so stay on the safe side and
613 LYXERR0("scrolling position not found!");
614 scrollDocView(d->scrollbarParameters_.max);
618 DocIterator dit = doc_iterator_begin(&buffer_);
620 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
625 // FIXME: this method is not working well.
626 void BufferView::setCursorFromScrollbar()
628 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
630 int const height = 2 * defaultRowHeight();
631 int const first = height;
632 int const last = height_ - height;
634 Cursor const & oldcur = d->cursor_;
636 switch (cursorStatus(oldcur)) {
644 int const y = getPos(oldcur, oldcur.boundary()).y_;
645 newy = min(last, max(y, first));
649 // We reset the cursor because cursorStatus() does not
650 // work when the cursor is within mathed.
653 tm.setCursorFromCoordinates(cur, 0, newy);
655 // update the bufferview cursor and notify insets
656 // FIXME: Care about the d->cursor_ flags to redraw if needed
657 Cursor old = d->cursor_;
659 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
661 d->cursor_.fixIfBroken();
665 Change const BufferView::getCurrentChange() const
667 if (!d->cursor_.selection())
668 return Change(Change::UNCHANGED);
670 DocIterator dit = d->cursor_.selectionBegin();
671 return dit.paragraph().lookupChange(dit.pos());
675 // this could be used elsewhere as well?
676 // FIXME: This does not work within mathed!
677 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
679 Point const p = getPos(dit, dit.boundary());
682 if (p.y_ > workHeight())
688 void BufferView::bookmarkEditPosition()
690 // Don't eat cpu time for each keystroke
691 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
694 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
698 void BufferView::saveBookmark(unsigned int idx)
700 // tentatively save bookmark, id and pos will be used to
701 // acturately locate a bookmark in a 'live' lyx session.
702 // pit and pos will be updated with bottom level pit/pos
704 if (!buffer_.isInternal()) {
705 theSession().bookmarks().save(
707 d->cursor_.bottom().pit(),
708 d->cursor_.bottom().pos(),
709 d->cursor_.paragraph().id(),
714 // emit message signal.
715 message(_("Save bookmark"));
720 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
721 int top_id, pos_type top_pos)
723 bool success = false;
726 d->cursor_.clearSelection();
728 // if a valid par_id is given, try it first
729 // This is the case for a 'live' bookmark when unique paragraph ID
730 // is used to track bookmarks.
732 dit = buffer_.getParFromID(top_id);
734 dit.pos() = min(dit.paragraph().size(), top_pos);
735 // Some slices of the iterator may not be
736 // reachable (e.g. closed collapsable inset)
737 // so the dociterator may need to be
738 // shortened. Otherwise, setCursor may crash
739 // lyx when the cursor can not be set to these
741 size_t const n = dit.depth();
742 for (size_t i = 0; i < n; ++i)
743 if (!dit[i].inset().editable()) {
751 // if top_id == 0, or searching through top_id failed
752 // This is the case for a 'restored' bookmark when only bottom
753 // (document level) pit was saved. Because of this, bookmark
754 // restoration is inaccurate. If a bookmark was within an inset,
755 // it will be restored to the left of the outmost inset that contains
757 if (bottom_pit < int(buffer_.paragraphs().size())) {
758 dit = doc_iterator_begin(&buffer_);
760 dit.pit() = bottom_pit;
761 dit.pos() = min(bottom_pos, dit.paragraph().size());
766 // Note: only bottom (document) level pit is set.
768 // set the current font.
769 d->cursor_.setCurrentFont();
770 // To center the screen on this new position we need the
771 // paragraph position which is computed at draw() time.
772 // So we need a redraw!
773 buffer_.changed(false);
782 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
784 if (lyxrc.rtl_support) {
785 if (d->cursor_.real_current_font.isRightToLeft()) {
786 if (d->intl_.keymap == Intl::PRIMARY)
787 d->intl_.keyMapSec();
789 if (d->intl_.keymap == Intl::SECONDARY)
790 d->intl_.keyMapPrim();
794 d->intl_.getTransManager().translateAndInsert(c, t, cur);
798 int BufferView::workWidth() const
804 void BufferView::recenter()
806 showCursor(d->cursor_, true);
810 void BufferView::showCursor()
812 showCursor(d->cursor_, false);
816 void BufferView::showCursor(DocIterator const & dit, bool recenter)
818 if (scrollToCursor(dit, recenter)) {
819 buffer_.changed(true);
820 updateHoveredInset();
825 void BufferView::scrollToCursor()
827 if (scrollToCursor(d->cursor_, false)) {
828 buffer_.changed(true);
829 updateHoveredInset();
834 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
836 // We are not properly started yet, delay until resizing is
841 LYXERR(Debug::SCROLLING, "recentering!");
843 CursorSlice const & bot = dit.bottom();
844 TextMetrics & tm = d->text_metrics_[bot.text()];
846 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
847 int bot_pit = bot.pit();
848 if (bot_pit > max_pit) {
849 // FIXME: Why does this happen?
850 LYXERR0("bottom pit is greater that max pit: "
851 << bot_pit << " > " << max_pit);
855 if (bot_pit == tm.first().first - 1)
856 tm.newParMetricsUp();
857 else if (bot_pit == tm.last().first + 1)
858 tm.newParMetricsDown();
860 if (tm.contains(bot_pit)) {
861 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
862 LASSERT(!pm.rows().empty(), /**/);
863 // FIXME: smooth scrolling doesn't work in mathed.
864 CursorSlice const & cs = dit.innerTextSlice();
865 int offset = coordOffset(dit, dit.boundary()).y_;
866 int ypos = pm.position() + offset;
867 Dimension const & row_dim =
868 pm.getRow(cs.pos(), dit.boundary()).dimension();
871 scrolled = scroll(ypos - height_/2);
872 else if (ypos - row_dim.ascent() < 0)
873 scrolled = scrollUp(- ypos + row_dim.ascent());
874 else if (ypos + row_dim.descent() > height_)
875 scrolled = scrollDown(ypos - height_ + defaultRowHeight() );
877 // else, nothing to do, the cursor is already visible so we just return.
878 return scrolled != 0;
881 // fix inline completion position
882 if (d->inlineCompletionPos_.fixIfBroken())
883 d->inlineCompletionPos_ = DocIterator();
885 tm.redoParagraph(bot_pit);
886 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
887 int offset = coordOffset(dit, dit.boundary()).y_;
889 d->anchor_pit_ = bot_pit;
890 CursorSlice const & cs = dit.innerTextSlice();
891 Dimension const & row_dim =
892 pm.getRow(cs.pos(), dit.boundary()).dimension();
895 d->anchor_ypos_ = height_/2;
896 else if (d->anchor_pit_ == 0)
897 d->anchor_ypos_ = offset + pm.ascent();
898 else if (d->anchor_pit_ == max_pit)
899 d->anchor_ypos_ = height_ - offset - row_dim.descent();
900 else if (offset > height_)
901 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
903 d->anchor_ypos_ = defaultRowHeight() * 2;
909 void BufferView::updateDocumentClass(DocumentClass const * const olddc)
911 message(_("Converting document to new document class..."));
913 StableDocIterator backcur(d->cursor_);
914 ErrorList & el = buffer_.errorList("Class Switch");
915 cap::switchBetweenClasses(
916 olddc, buffer_.params().documentClassPtr(),
917 static_cast<InsetText &>(buffer_.inset()), el);
919 setCursor(backcur.asDocIterator(&buffer_));
921 buffer_.errors("Class Switch");
922 buffer_.updateBuffer();
925 /** Return the change status at cursor position, taking in account the
926 * status at each level of the document iterator (a table in a deleted
927 * footnote is deleted).
928 * When \param outer is true, the top slice is not looked at.
930 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
932 size_t const depth = dit.depth() - (outer ? 1 : 0);
934 for (size_t i = 0 ; i < depth ; ++i) {
935 CursorSlice const & slice = dit[i];
936 if (!slice.inset().inMathed()
937 && slice.pos() < slice.paragraph().size()) {
938 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
939 if (ch != Change::UNCHANGED)
943 return Change::UNCHANGED;
947 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
949 // Can we use a readonly buffer?
950 if (buffer_.isReadonly()
951 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
952 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
953 flag.message(from_utf8(N_("Document is read-only")));
954 flag.setEnabled(false);
957 // Are we in a DELETED change-tracking region?
958 if (lookupChangeType(d->cursor_, true) == Change::DELETED
959 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
960 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
961 flag.message(from_utf8(N_("This portion of the document is deleted.")));
962 flag.setEnabled(false);
966 Cursor & cur = d->cursor_;
968 if (cur.getStatus(cmd, flag))
971 switch (cmd.action) {
973 // FIXME: This is a bit problematic because we don't check if this is
974 // a document BufferView or not for these LFUNs. We probably have to
975 // dispatch both to currentBufferView() and, if that fails,
976 // to documentBufferView(); same as we do know for current Buffer and
977 // document Buffer. Ideally those LFUN should go to Buffer as they*
978 // operate on the full Buffer and the cursor is only needed either for
979 // an Undo record or to restore a cursor position. But we don't know
980 // how to do that inside Buffer of course.
981 case LFUN_BUFFER_PARAMS_APPLY:
982 case LFUN_LAYOUT_MODULES_CLEAR:
983 case LFUN_LAYOUT_MODULE_ADD:
984 case LFUN_LAYOUT_RELOAD:
985 case LFUN_TEXTCLASS_APPLY:
986 case LFUN_TEXTCLASS_LOAD:
987 flag.setEnabled(!buffer_.isReadonly());
991 flag.setEnabled(buffer_.undo().hasUndoStack());
994 flag.setEnabled(buffer_.undo().hasRedoStack());
996 case LFUN_FILE_INSERT:
997 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
998 case LFUN_FILE_INSERT_PLAINTEXT:
999 case LFUN_BOOKMARK_SAVE:
1000 // FIXME: Actually, these LFUNS should be moved to Text
1001 flag.setEnabled(cur.inTexted());
1004 case LFUN_FONT_STATE:
1005 case LFUN_LABEL_INSERT:
1006 case LFUN_INFO_INSERT:
1007 case LFUN_INSET_EDIT:
1008 case LFUN_PARAGRAPH_GOTO:
1009 case LFUN_NOTE_NEXT:
1010 case LFUN_REFERENCE_NEXT:
1011 case LFUN_WORD_FIND:
1012 case LFUN_WORD_FIND_FORWARD:
1013 case LFUN_WORD_FIND_BACKWARD:
1014 case LFUN_WORD_FINDADV:
1015 case LFUN_WORD_REPLACE:
1018 case LFUN_MARK_TOGGLE:
1019 case LFUN_SCREEN_RECENTER:
1020 case LFUN_SCREEN_SHOW_CURSOR:
1021 case LFUN_BIBTEX_DATABASE_ADD:
1022 case LFUN_BIBTEX_DATABASE_DEL:
1023 case LFUN_STATISTICS:
1024 case LFUN_BRANCH_ADD_INSERT:
1025 case LFUN_KEYMAP_OFF:
1026 case LFUN_KEYMAP_PRIMARY:
1027 case LFUN_KEYMAP_SECONDARY:
1028 case LFUN_KEYMAP_TOGGLE:
1029 flag.setEnabled(true);
1032 case LFUN_LABEL_COPY_AS_REF: {
1033 // if there is an inset at cursor, see whether it
1035 Inset * inset = cur.nextInset();
1036 if (!inset || !inset->getStatus(cur, cmd, flag))
1037 flag.setEnabled(false);
1041 case LFUN_LABEL_GOTO: {
1042 flag.setEnabled(!cmd.argument().empty()
1043 || getInsetByCode<InsetRef>(cur, REF_CODE));
1047 case LFUN_CHANGES_TRACK:
1048 flag.setEnabled(true);
1049 flag.setOnOff(buffer_.params().trackChanges);
1052 case LFUN_CHANGES_OUTPUT:
1053 flag.setEnabled(true);
1054 flag.setOnOff(buffer_.params().outputChanges);
1057 case LFUN_CHANGES_MERGE:
1058 case LFUN_CHANGE_NEXT:
1059 case LFUN_CHANGE_PREVIOUS:
1060 case LFUN_ALL_CHANGES_ACCEPT:
1061 case LFUN_ALL_CHANGES_REJECT:
1062 // TODO: context-sensitive enabling of LFUNs
1063 // In principle, these command should only be enabled if there
1064 // is a change in the document. However, without proper
1065 // optimizations, this will inevitably result in poor performance.
1066 flag.setEnabled(true);
1069 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1070 flag.setOnOff(buffer_.params().compressed);
1074 case LFUN_SCREEN_UP:
1075 case LFUN_SCREEN_DOWN:
1077 case LFUN_SCREEN_UP_SELECT:
1078 case LFUN_SCREEN_DOWN_SELECT:
1079 case LFUN_INSET_FORALL:
1080 flag.setEnabled(true);
1083 case LFUN_LAYOUT_TABULAR:
1084 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1088 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1091 case LFUN_LAYOUT_PARAGRAPH:
1092 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1095 case LFUN_DIALOG_SHOW_NEW_INSET:
1096 // FIXME: this is wrong, but I do not understand the
1098 if (cur.inset().lyxCode() == CAPTION_CODE)
1099 return cur.inset().getStatus(cur, cmd, flag);
1100 // FIXME we should consider passthru paragraphs too.
1101 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1104 case LFUN_CITATION_INSERT: {
1105 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1106 // FIXME: This could turn in a recursive hell.
1107 // Shouldn't we use Buffer::getStatus() instead?
1108 flag.setEnabled(lyx::getStatus(fr).enabled());
1111 case LFUN_INSET_APPLY: {
1112 string const name = cmd.getArg(0);
1113 Inset * inset = editedInset(name);
1115 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1117 if (!inset->getStatus(cur, fr, fs)) {
1118 // Every inset is supposed to handle this
1119 LASSERT(false, break);
1123 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1124 flag |= lyx::getStatus(fr);
1130 flag.setEnabled(false);
1138 Inset * BufferView::editedInset(string const & name) const
1140 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1141 return it == d->edited_insets_.end() ? 0 : it->second;
1145 void BufferView::editInset(string const & name, Inset * inset)
1147 d->edited_insets_[name] = inset;
1151 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1153 //lyxerr << [ cmd = " << cmd << "]" << endl;
1155 // Make sure that the cached BufferView is correct.
1156 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1157 << " arg[" << to_utf8(cmd.argument()) << ']'
1158 << " x[" << cmd.x << ']'
1159 << " y[" << cmd.y << ']'
1160 << " button[" << cmd.button() << ']');
1162 string const argument = to_utf8(cmd.argument());
1163 Cursor & cur = d->cursor_;
1165 // Don't dispatch function that does not apply to internal buffers.
1166 if (buffer_.isInternal()
1167 && lyxaction.funcHasFlag(cmd.action, LyXAction::NoInternal))
1170 // We'll set this back to false if need be.
1171 bool dispatched = true;
1172 buffer_.undo().beginUndoGroup();
1174 switch (cmd.action) {
1176 case LFUN_BUFFER_PARAMS_APPLY: {
1177 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1178 cur.recordUndoFullDocument();
1179 istringstream ss(to_utf8(cmd.argument()));
1182 int const unknown_tokens = buffer_.readHeader(lex);
1183 if (unknown_tokens != 0) {
1184 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1185 << unknown_tokens << " unknown token"
1186 << (unknown_tokens == 1 ? "" : "s"));
1188 updateDocumentClass(oldClass);
1190 // We are most certainly here because of a change in the document
1191 // It is then better to make sure that all dialogs are in sync with
1192 // current document settings.
1193 dr.update(Update::Force | Update::FitCursor);
1197 case LFUN_LAYOUT_MODULES_CLEAR: {
1198 DocumentClass const * const oldClass =
1199 buffer_.params().documentClassPtr();
1200 cur.recordUndoFullDocument();
1201 buffer_.params().clearLayoutModules();
1202 buffer_.params().makeDocumentClass();
1203 updateDocumentClass(oldClass);
1204 dr.update(Update::Force | Update::FitCursor);
1208 case LFUN_LAYOUT_MODULE_ADD: {
1209 BufferParams const & params = buffer_.params();
1210 if (!params.moduleCanBeAdded(argument)) {
1211 LYXERR0("Module `" << argument <<
1212 "' cannot be added due to failed requirements or "
1213 "conflicts with installed modules.");
1216 DocumentClass const * const oldClass = params.documentClassPtr();
1217 cur.recordUndoFullDocument();
1218 buffer_.params().addLayoutModule(argument);
1219 buffer_.params().makeDocumentClass();
1220 updateDocumentClass(oldClass);
1221 dr.update(Update::Force | Update::FitCursor);
1225 case LFUN_TEXTCLASS_APPLY: {
1226 if (!LayoutFileList::get().load(argument, buffer_.temppath()) &&
1227 !LayoutFileList::get().load(argument, buffer_.filePath()))
1230 LayoutFile const * old_layout = buffer_.params().baseClass();
1231 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1233 if (old_layout == new_layout)
1237 //Save the old, possibly modular, layout for use in conversion.
1238 DocumentClass const * const oldDocClass =
1239 buffer_.params().documentClassPtr();
1240 cur.recordUndoFullDocument();
1241 buffer_.params().setBaseClass(argument);
1242 buffer_.params().makeDocumentClass();
1243 updateDocumentClass(oldDocClass);
1244 dr.update(Update::Force | Update::FitCursor);
1248 case LFUN_TEXTCLASS_LOAD:
1249 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1250 LayoutFileList::get().load(argument, buffer_.filePath());
1253 case LFUN_LAYOUT_RELOAD: {
1254 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1255 LayoutFileIndex bc = buffer_.params().baseClassID();
1256 LayoutFileList::get().reset(bc);
1257 buffer_.params().setBaseClass(bc);
1258 buffer_.params().makeDocumentClass();
1259 updateDocumentClass(oldClass);
1260 dr.update(Update::Force | Update::FitCursor);
1265 dr.setMessage(_("Undo"));
1266 cur.clearSelection();
1267 if (!cur.textUndo())
1268 dr.setMessage(_("No further undo information"));
1270 dr.update(Update::Force | Update::FitCursor);
1274 dr.setMessage(_("Redo"));
1275 cur.clearSelection();
1276 if (!cur.textRedo())
1277 dr.setMessage(_("No further redo information"));
1279 dr.update(Update::Force | Update::FitCursor);
1282 case LFUN_FONT_STATE:
1283 dr.setMessage(cur.currentState());
1286 case LFUN_BOOKMARK_SAVE:
1287 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1290 case LFUN_LABEL_GOTO: {
1291 docstring label = cmd.argument();
1292 if (label.empty()) {
1294 getInsetByCode<InsetRef>(cur, REF_CODE);
1296 label = inset->getParam("reference");
1297 // persistent=false: use temp_bookmark
1306 case LFUN_INSET_EDIT: {
1307 FuncRequest fr(cmd);
1308 // if there is an inset at cursor, see whether it
1310 Inset * inset = cur.nextInset();
1312 inset->dispatch(cur, fr);
1313 // if it did not work, try the underlying inset.
1314 if (!inset || !cur.result().dispatched())
1317 // FIXME I'm adding the last break to solve a crash,
1318 // but that is obviously not right.
1319 if (!cur.result().dispatched())
1320 // It did not work too; no action needed.
1325 case LFUN_PARAGRAPH_GOTO: {
1326 int const id = convert<int>(cmd.getArg(0));
1327 int const pos = convert<int>(cmd.getArg(1));
1329 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1330 b = theBufferList().next(b)) {
1332 DocIterator dit = b->getParFromID(id);
1334 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1338 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1339 << " found in buffer `"
1340 << b->absFileName() << "'.");
1342 if (b == &buffer_) {
1346 dr.update(Update::Force | Update::FitCursor);
1348 // Switch to other buffer view and resend cmd
1349 lyx::dispatch(FuncRequest(
1350 LFUN_BUFFER_SWITCH, b->absFileName()));
1358 case LFUN_NOTE_NEXT:
1359 gotoInset(this, NOTE_CODE, false);
1362 case LFUN_REFERENCE_NEXT: {
1363 vector<InsetCode> tmp;
1364 tmp.push_back(LABEL_CODE);
1365 tmp.push_back(REF_CODE);
1366 gotoInset(this, tmp, true);
1370 case LFUN_CHANGES_TRACK:
1371 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1374 case LFUN_CHANGES_OUTPUT:
1375 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1376 if (buffer_.params().outputChanges) {
1377 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1378 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1379 LaTeXFeatures::isAvailable("xcolor");
1381 if (!dvipost && !xcolorulem) {
1382 Alert::warning(_("Changes not shown in LaTeX output"),
1383 _("Changes will not be highlighted in LaTeX output, "
1384 "because neither dvipost nor xcolor/ulem are installed.\n"
1385 "Please install these packages or redefine "
1386 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1387 } else if (!xcolorulem) {
1388 Alert::warning(_("Changes not shown in LaTeX output"),
1389 _("Changes will not be highlighted in LaTeX output "
1390 "when using pdflatex, because xcolor and ulem are not installed.\n"
1391 "Please install both packages or redefine "
1392 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1397 case LFUN_CHANGE_NEXT:
1398 findNextChange(this);
1399 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1400 dr.update(Update::Force | Update::FitCursor);
1403 case LFUN_CHANGE_PREVIOUS:
1404 findPreviousChange(this);
1405 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1406 dr.update(Update::Force | Update::FitCursor);
1409 case LFUN_CHANGES_MERGE:
1410 if (findNextChange(this) || findPreviousChange(this)) {
1411 dr.update(Update::Force | Update::FitCursor);
1412 showDialog("changes");
1416 case LFUN_ALL_CHANGES_ACCEPT:
1417 // select complete document
1419 cur.selHandle(true);
1420 buffer_.text().cursorBottom(cur);
1421 // accept everything in a single step to support atomic undo
1422 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1423 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1424 dr.update(Update::Force | Update::FitCursor);
1427 case LFUN_ALL_CHANGES_REJECT:
1428 // select complete document
1430 cur.selHandle(true);
1431 buffer_.text().cursorBottom(cur);
1432 // reject everything in a single step to support atomic undo
1433 // Note: reject does not work recursively; the user may have to repeat the operation
1434 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1435 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1436 dr.update(Update::Force | Update::FitCursor);
1439 case LFUN_WORD_FIND_FORWARD:
1440 case LFUN_WORD_FIND_BACKWARD: {
1441 static docstring last_search;
1442 docstring searched_string;
1444 if (!cmd.argument().empty()) {
1445 last_search = cmd.argument();
1446 searched_string = cmd.argument();
1448 searched_string = last_search;
1451 if (searched_string.empty())
1454 bool const fw = cmd.action == LFUN_WORD_FIND_FORWARD;
1455 docstring const data =
1456 find2string(searched_string, true, false, fw);
1457 find(this, FuncRequest(LFUN_WORD_FIND, data));
1461 case LFUN_WORD_FIND: {
1462 FuncRequest req = cmd;
1463 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1464 req = d->search_request_cache_;
1465 if (req.argument().empty()) {
1466 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1469 if (find(this, req))
1472 message(_("String not found!"));
1473 d->search_request_cache_ = req;
1477 case LFUN_WORD_REPLACE: {
1478 bool has_deleted = false;
1479 if (cur.selection()) {
1480 DocIterator beg = cur.selectionBegin();
1481 DocIterator end = cur.selectionEnd();
1482 if (beg.pit() == end.pit()) {
1483 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1485 && cur.paragraph().isDeleted(p))
1490 replace(this, cmd, has_deleted);
1494 case LFUN_WORD_FINDADV: {
1495 FindAndReplaceOptions opt;
1496 istringstream iss(to_utf8(cmd.argument()));
1498 if (findAdv(this, opt))
1506 cur.clearSelection();
1507 dr.setMessage(from_utf8(N_("Mark off")));
1511 cur.clearSelection();
1513 dr.setMessage(from_utf8(N_("Mark on")));
1516 case LFUN_MARK_TOGGLE:
1517 cur.setSelection(false);
1520 dr.setMessage(from_utf8(N_("Mark removed")));
1523 dr.setMessage(from_utf8(N_("Mark set")));
1528 case LFUN_SCREEN_SHOW_CURSOR:
1532 case LFUN_SCREEN_RECENTER:
1536 case LFUN_BIBTEX_DATABASE_ADD: {
1537 Cursor tmpcur = cur;
1538 findInset(tmpcur, BIBTEX_CODE, false);
1539 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1542 if (inset->addDatabase(cmd.argument()))
1543 buffer_.updateBibfilesCache();
1548 case LFUN_BIBTEX_DATABASE_DEL: {
1549 Cursor tmpcur = cur;
1550 findInset(tmpcur, BIBTEX_CODE, false);
1551 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1554 if (inset->delDatabase(cmd.argument()))
1555 buffer_.updateBibfilesCache();
1560 case LFUN_STATISTICS: {
1561 DocIterator from, to;
1562 if (cur.selection()) {
1563 from = cur.selectionBegin();
1564 to = cur.selectionEnd();
1566 from = doc_iterator_begin(&buffer_);
1567 to = doc_iterator_end(&buffer_);
1569 int const words = countWords(from, to);
1570 int const chars = countChars(from, to, false);
1571 int const chars_blanks = countChars(from, to, true);
1573 if (cur.selection())
1574 message = _("Statistics for the selection:");
1576 message = _("Statistics for the document:");
1579 message += bformat(_("%1$d words"), words);
1581 message += _("One word");
1583 if (chars_blanks != 1)
1584 message += bformat(_("%1$d characters (including blanks)"),
1587 message += _("One character (including blanks)");
1590 message += bformat(_("%1$d characters (excluding blanks)"),
1593 message += _("One character (excluding blanks)");
1595 Alert::information(_("Statistics"), message);
1599 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1600 // turn compression on/off
1601 buffer_.params().compressed = !buffer_.params().compressed;
1604 case LFUN_LABEL_COPY_AS_REF: {
1605 // if there is an inset at cursor, try to copy it
1606 Inset * inset = &cur.inset();
1607 if (!inset || !inset->asInsetMath())
1608 inset = cur.nextInset();
1610 FuncRequest tmpcmd = cmd;
1611 inset->dispatch(cur, tmpcmd);
1613 if (!cur.result().dispatched())
1614 // It did not work too; no action needed.
1616 cur.clearSelection();
1617 dr.update(Update::SinglePar | Update::FitCursor);
1621 case LFUN_SCREEN_UP:
1622 case LFUN_SCREEN_DOWN: {
1623 Point p = getPos(cur, cur.boundary());
1624 // This code has been commented out to enable to scroll down a
1625 // document, even if there are large insets in it (see bug #5465).
1626 /*if (p.y_ < 0 || p.y_ > height_) {
1627 // The cursor is off-screen so recenter before proceeding.
1629 p = getPos(cur, cur.boundary());
1631 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1632 ? -height_ : height_);
1633 if (cmd.action == LFUN_SCREEN_UP && scrolled > -height_)
1635 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1636 p = Point(width_, height_);
1638 bool const in_texted = cur.inTexted();
1640 buffer_.changed(true);
1641 updateHoveredInset();
1643 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1644 true, cmd.action == LFUN_SCREEN_UP);
1645 //FIXME: what to do with cur.x_target()?
1646 bool update = in_texted && cur.bv().checkDepm(cur, old);
1649 dr.update(Update::Force | Update::FitCursor);
1657 case LFUN_SCREEN_UP_SELECT: {
1658 cur.selHandle(true);
1659 if (isTopScreen()) {
1660 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1664 int y = getPos(cur, cur.boundary()).y_;
1665 int const ymin = y - height_ + defaultRowHeight();
1666 while (y > ymin && cur.up())
1667 y = getPos(cur, cur.boundary()).y_;
1670 dr.update(Update::SinglePar | Update::FitCursor);
1674 case LFUN_SCREEN_DOWN_SELECT: {
1675 cur.selHandle(true);
1676 if (isBottomScreen()) {
1677 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1681 int y = getPos(cur, cur.boundary()).y_;
1682 int const ymax = y + height_ - defaultRowHeight();
1683 while (y < ymax && cur.down())
1684 y = getPos(cur, cur.boundary()).y_;
1687 dr.update(Update::SinglePar | Update::FitCursor);
1692 // This would be in Buffer class if only Cursor did not
1693 // require a bufferview
1694 case LFUN_INSET_FORALL: {
1695 docstring const name = from_utf8(cmd.getArg(0));
1696 string const commandstr = cmd.getLongArg(1);
1697 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1699 // an arbitrary number to limit number of iterations
1700 const int max_iter = 10000;
1702 Cursor & cur = d->cursor_;
1703 Cursor const savecur = cur;
1705 if (!cur.nextInset())
1707 cur.beginUndoGroup();
1708 while(cur && iterations < max_iter) {
1709 Inset * ins = cur.nextInset();
1712 docstring insname = ins->name();
1713 while (!insname.empty()) {
1714 if (insname == name || name == from_utf8("*")) {
1716 lyx::dispatch(fr, dr);
1720 size_t const i = insname.rfind(':');
1721 if (i == string::npos)
1723 insname = insname.substr(0, i);
1730 dr.update(Update::Force);
1732 if (iterations >= max_iter) {
1734 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1736 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1741 case LFUN_BRANCH_ADD_INSERT: {
1742 docstring branch_name = from_utf8(cmd.getArg(0));
1743 if (branch_name.empty())
1744 if (!Alert::askForText(branch_name, _("Branch name")) ||
1745 branch_name.empty())
1748 DispatchResult drtmp;
1749 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1750 if (drtmp.error()) {
1751 Alert::warning(_("Branch already exists"), drtmp.message());
1754 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1758 case LFUN_KEYMAP_OFF:
1759 getIntl().keyMapOn(false);
1762 case LFUN_KEYMAP_PRIMARY:
1763 getIntl().keyMapPrim();
1766 case LFUN_KEYMAP_SECONDARY:
1767 getIntl().keyMapSec();
1770 case LFUN_KEYMAP_TOGGLE:
1771 getIntl().toggleKeyMap();
1774 case LFUN_DIALOG_SHOW_NEW_INSET: {
1775 string const name = cmd.getArg(0);
1776 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1777 if (decodeInsetParam(name, data, buffer_))
1778 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1780 lyxerr << "Inset type '" << name <<
1781 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1785 case LFUN_CITATION_INSERT: {
1786 if (argument.empty()) {
1787 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1790 // we can have one optional argument, delimited by '|'
1791 // citation-insert <key>|<text_before>
1792 // this should be enhanced to also support text_after
1793 // and citation style
1794 string arg = argument;
1796 if (contains(argument, "|")) {
1797 arg = token(argument, '|', 0);
1798 opt1 = token(argument, '|', 1);
1800 InsetCommandParams icp(CITE_CODE);
1801 icp["key"] = from_utf8(arg);
1803 icp["before"] = from_utf8(opt1);
1804 string icstr = InsetCommand::params2string("citation", icp);
1805 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1810 case LFUN_INSET_APPLY: {
1811 string const name = cmd.getArg(0);
1812 Inset * inset = editedInset(name);
1814 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1818 // put cursor in front of inset.
1819 if (!setCursorFromInset(inset)) {
1820 LASSERT(false, break);
1823 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1824 inset->dispatch(cur, fr);
1825 dr.update(Update::SinglePar | Update::FitCursor);
1834 buffer_.undo().endUndoGroup();
1835 dr.dispatched(dispatched);
1840 docstring const BufferView::requestSelection()
1842 Cursor & cur = d->cursor_;
1844 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1845 if (!cur.selection()) {
1846 d->xsel_cache_.set = false;
1850 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1851 if (!d->xsel_cache_.set ||
1852 cur.top() != d->xsel_cache_.cursor ||
1853 cur.anchor_.top() != d->xsel_cache_.anchor)
1855 d->xsel_cache_.cursor = cur.top();
1856 d->xsel_cache_.anchor = cur.anchor_.top();
1857 d->xsel_cache_.set = cur.selection();
1858 return cur.selectionAsString(false);
1864 void BufferView::clearSelection()
1866 d->cursor_.clearSelection();
1867 // Clear the selection buffer. Otherwise a subsequent
1868 // middle-mouse-button paste would use the selection buffer,
1869 // not the more current external selection.
1870 cap::clearSelection();
1871 d->xsel_cache_.set = false;
1872 // The buffer did not really change, but this causes the
1873 // redraw we need because we cleared the selection above.
1874 buffer_.changed(false);
1878 void BufferView::resize(int width, int height)
1880 // Update from work area
1884 // Clear the paragraph height cache.
1885 d->par_height_.clear();
1886 // Redo the metrics.
1891 Inset const * BufferView::getCoveringInset(Text const & text,
1894 TextMetrics & tm = d->text_metrics_[&text];
1895 Inset * inset = tm.checkInsetHit(x, y);
1899 if (!inset->descendable(*this))
1900 // No need to go further down if the inset is not
1904 size_t cell_number = inset->nargs();
1905 // Check all the inner cell.
1906 for (size_t i = 0; i != cell_number; ++i) {
1907 Text const * inner_text = inset->getText(i);
1910 Inset const * inset_deeper =
1911 getCoveringInset(*inner_text, x, y);
1913 return inset_deeper;
1921 void BufferView::updateHoveredInset() const
1923 // Get inset under mouse, if there is one.
1924 Inset const * covering_inset = getCoveringInset(buffer_.text(),
1925 d->mouse_position_cache_.x_, d->mouse_position_cache_.y_);
1926 if (covering_inset == d->last_inset_)
1927 // Same inset, no need to do anything...
1930 bool need_redraw = false;
1932 // Remove the hint on the last hovered inset (if any).
1933 need_redraw |= d->last_inset_->setMouseHover(false);
1935 // const_cast because of setMouseHover().
1936 Inset * inset = const_cast<Inset *>(covering_inset);
1938 // Highlight the newly hovered inset (if any).
1939 need_redraw |= inset->setMouseHover(true);
1941 d->last_inset_ = inset;
1944 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1945 << d->mouse_position_cache_.x_ << ", "
1946 << d->mouse_position_cache_.y_ << ")");
1948 d->update_strategy_ = DecorationUpdate;
1950 // This event (moving without mouse click) is not passed further.
1951 // This should be changed if it is further utilized.
1952 buffer_.changed(false);
1957 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1959 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1961 // This is only called for mouse related events including
1962 // LFUN_FILE_OPEN generated by drag-and-drop.
1963 FuncRequest cmd = cmd0;
1965 Cursor old = cursor();
1967 cur.push(buffer_.inset());
1968 cur.setSelection(d->cursor_.selection());
1970 // Either the inset under the cursor or the
1971 // surrounding Text will handle this event.
1973 // make sure we stay within the screen...
1974 cmd.y = min(max(cmd.y, -1), height_);
1976 d->mouse_position_cache_.x_ = cmd.x;
1977 d->mouse_position_cache_.y_ = cmd.y;
1979 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1980 updateHoveredInset();
1984 // Build temporary cursor.
1985 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1987 // Put anchor at the same position.
1990 cur.beginUndoGroup();
1992 // Try to dispatch to an non-editable inset near this position
1993 // via the temp cursor. If the inset wishes to change the real
1994 // cursor it has to do so explicitly by using
1995 // cur.bv().cursor() = cur; (or similar)
1997 inset->dispatch(cur, cmd);
1999 // Now dispatch to the temporary cursor. If the real cursor should
2000 // be modified, the inset's dispatch has to do so explicitly.
2001 if (!inset || !cur.result().dispatched())
2006 // Notify left insets
2009 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2011 cursor().fixIfBroken();
2014 // Do we have a selection?
2015 theSelection().haveSelection(cursor().selection());
2017 // If the command has been dispatched,
2018 if (cur.result().dispatched() || cur.result().update())
2019 processUpdateFlags(cur.result().update());
2023 void BufferView::lfunScroll(FuncRequest const & cmd)
2025 string const scroll_type = cmd.getArg(0);
2026 int scroll_step = 0;
2027 if (scroll_type == "line")
2028 scroll_step = d->scrollbarParameters_.single_step;
2029 else if (scroll_type == "page")
2030 scroll_step = d->scrollbarParameters_.page_step;
2033 string const scroll_quantity = cmd.getArg(1);
2034 if (scroll_quantity == "up")
2035 scrollUp(scroll_step);
2036 else if (scroll_quantity == "down")
2037 scrollDown(scroll_step);
2039 int const scroll_value = convert<int>(scroll_quantity);
2041 scroll(scroll_step * scroll_value);
2043 buffer_.changed(true);
2044 updateHoveredInset();
2048 int BufferView::minVisiblePart()
2050 return 2 * defaultRowHeight();
2054 int BufferView::scroll(int y)
2057 return scrollDown(y);
2059 return scrollUp(-y);
2064 int BufferView::scrollDown(int offset)
2066 Text * text = &buffer_.text();
2067 TextMetrics & tm = d->text_metrics_[text];
2068 int const ymax = height_ + offset;
2070 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2071 int bottom_pos = last.second->position() + last.second->descent();
2072 if (lyxrc.scroll_below_document)
2073 bottom_pos += height_ - minVisiblePart();
2074 if (last.first + 1 == int(text->paragraphs().size())) {
2075 if (bottom_pos <= height_)
2077 offset = min(offset, bottom_pos - height_);
2080 if (bottom_pos > ymax)
2082 tm.newParMetricsDown();
2084 d->anchor_ypos_ -= offset;
2089 int BufferView::scrollUp(int offset)
2091 Text * text = &buffer_.text();
2092 TextMetrics & tm = d->text_metrics_[text];
2093 int ymin = - offset;
2095 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2096 int top_pos = first.second->position() - first.second->ascent();
2097 if (first.first == 0) {
2100 offset = min(offset, - top_pos);
2105 tm.newParMetricsUp();
2107 d->anchor_ypos_ += offset;
2112 void BufferView::setCursorFromRow(int row)
2117 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2121 buffer_.text().setCursor(d->cursor_, 0, 0);
2123 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
2128 bool BufferView::setCursorFromInset(Inset const * inset)
2130 // are we already there?
2131 if (cursor().nextInset() == inset)
2134 // Inset is not at cursor position. Find it in the document.
2137 while (cur && cur.nextInset() != inset)
2148 void BufferView::gotoLabel(docstring const & label)
2150 std::vector<Buffer const *> bufs = buffer().allRelatives();
2151 std::vector<Buffer const *>::iterator it = bufs.begin();
2152 for (; it != bufs.end(); ++it) {
2153 Buffer const * buf = *it;
2156 Toc & toc = buf->tocBackend().toc("label");
2157 TocIterator toc_it = toc.begin();
2158 TocIterator end = toc.end();
2159 for (; toc_it != end; ++toc_it) {
2160 if (label == toc_it->str()) {
2161 lyx::dispatch(toc_it->action());
2169 TextMetrics const & BufferView::textMetrics(Text const * t) const
2171 return const_cast<BufferView *>(this)->textMetrics(t);
2175 TextMetrics & BufferView::textMetrics(Text const * t)
2177 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2178 if (tmc_it == d->text_metrics_.end()) {
2179 tmc_it = d->text_metrics_.insert(
2180 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2182 return tmc_it->second;
2186 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2189 return textMetrics(t).parMetrics(pit);
2193 int BufferView::workHeight() const
2199 void BufferView::setCursor(DocIterator const & dit)
2202 size_t const n = dit.depth();
2203 for (size_t i = 0; i < n; ++i)
2204 dit[i].inset().edit(d->cursor_, true);
2206 d->cursor_.setCursor(dit);
2207 d->cursor_.setSelection(false);
2211 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2213 // Would be wrong to delete anything if we have a selection.
2214 if (cur.selection())
2217 bool need_anchor_change = false;
2218 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2219 need_anchor_change);
2221 if (need_anchor_change)
2229 buffer_.updateBuffer();
2230 buffer_.changed(true);
2235 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2237 LASSERT(&cur.bv() == this, /**/);
2240 // this event will clear selection so we save selection for
2241 // persistent selection
2242 cap::saveSelection(cursor());
2244 d->cursor_.macroModeClose();
2246 // Has the cursor just left the inset?
2247 bool leftinset = (&d->cursor_.inset() != &cur.inset());
2249 d->cursor_.fixIfBroken();
2251 // FIXME: shift-mouse selection doesn't work well across insets.
2252 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
2254 // do the dEPM magic if needed
2255 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2256 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2257 // the leftinset bool would not be necessary (badcursor instead).
2258 bool update = leftinset;
2259 if (!do_selection && d->cursor_.inTexted())
2260 update |= checkDepm(cur, d->cursor_);
2263 d->cursor_.resetAnchor();
2264 d->cursor_.setCursor(cur);
2265 d->cursor_.boundary(cur.boundary());
2267 d->cursor_.setSelection();
2269 d->cursor_.clearSelection();
2271 d->cursor_.finishUndo();
2272 d->cursor_.setCurrentFont();
2277 void BufferView::putSelectionAt(DocIterator const & cur,
2278 int length, bool backwards)
2280 d->cursor_.clearSelection();
2286 d->cursor_.pos() += length;
2287 d->cursor_.setSelection(d->cursor_, -length);
2289 d->cursor_.setSelection(d->cursor_, length);
2291 // Ensure a redraw happens in any case because the new selection could
2292 // possibly be on the same screen as the previous selection.
2293 processUpdateFlags(Update::Force | Update::FitCursor);
2297 Cursor & BufferView::cursor()
2303 Cursor const & BufferView::cursor() const
2309 pit_type BufferView::anchor_ref() const
2311 return d->anchor_pit_;
2315 bool BufferView::singleParUpdate()
2317 Text & buftext = buffer_.text();
2318 pit_type const bottom_pit = d->cursor_.bottom().pit();
2319 TextMetrics & tm = textMetrics(&buftext);
2320 int old_height = tm.parMetrics(bottom_pit).height();
2322 // make sure inline completion pointer is ok
2323 if (d->inlineCompletionPos_.fixIfBroken())
2324 d->inlineCompletionPos_ = DocIterator();
2326 // In Single Paragraph mode, rebreak only
2327 // the (main text, not inset!) paragraph containing the cursor.
2328 // (if this paragraph contains insets etc., rebreaking will
2329 // recursively descend)
2330 tm.redoParagraph(bottom_pit);
2331 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2332 if (pm.height() != old_height)
2333 // Paragraph height has changed so we cannot proceed to
2334 // the singlePar optimisation.
2337 d->update_strategy_ = SingleParUpdate;
2339 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2340 << " y2: " << pm.position() + pm.descent()
2341 << " pit: " << bottom_pit
2342 << " singlepar: 1");
2347 void BufferView::updateMetrics()
2349 if (height_ == 0 || width_ == 0)
2352 Text & buftext = buffer_.text();
2353 pit_type const npit = int(buftext.paragraphs().size());
2355 // Clear out the position cache in case of full screen redraw,
2356 d->coord_cache_.clear();
2358 // Clear out paragraph metrics to avoid having invalid metrics
2359 // in the cache from paragraphs not relayouted below
2360 // The complete text metrics will be redone.
2361 d->text_metrics_.clear();
2363 TextMetrics & tm = textMetrics(&buftext);
2365 // make sure inline completion pointer is ok
2366 if (d->inlineCompletionPos_.fixIfBroken())
2367 d->inlineCompletionPos_ = DocIterator();
2369 if (d->anchor_pit_ >= npit)
2370 // The anchor pit must have been deleted...
2371 d->anchor_pit_ = npit - 1;
2373 // Rebreak anchor paragraph.
2374 tm.redoParagraph(d->anchor_pit_);
2375 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2378 if (d->anchor_pit_ == 0) {
2379 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2381 // Complete buffer visible? Then it's easy.
2382 if (scrollRange == 0)
2383 d->anchor_ypos_ = anchor_pm.ascent();
2385 // FIXME: Some clever handling needed to show
2386 // the _first_ paragraph up to the top if the cursor is
2387 // in the first line.
2389 anchor_pm.setPosition(d->anchor_ypos_);
2391 LYXERR(Debug::PAINTING, "metrics: "
2392 << " anchor pit = " << d->anchor_pit_
2393 << " anchor ypos = " << d->anchor_ypos_);
2395 // Redo paragraphs above anchor if necessary.
2396 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2397 // We are now just above the anchor paragraph.
2398 pit_type pit1 = d->anchor_pit_ - 1;
2399 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2400 tm.redoParagraph(pit1);
2401 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2403 // Save the paragraph position in the cache.
2408 // Redo paragraphs below the anchor if necessary.
2409 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2410 // We are now just below the anchor paragraph.
2411 pit_type pit2 = d->anchor_pit_ + 1;
2412 for (; pit2 < npit && y2 <= height_; ++pit2) {
2413 tm.redoParagraph(pit2);
2414 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2416 // Save the paragraph position in the cache.
2421 LYXERR(Debug::PAINTING, "Metrics: "
2422 << " anchor pit = " << d->anchor_pit_
2423 << " anchor ypos = " << d->anchor_ypos_
2426 << " pit1 = " << pit1
2427 << " pit2 = " << pit2);
2429 d->update_strategy_ = FullScreenUpdate;
2431 if (lyxerr.debugging(Debug::WORKAREA)) {
2432 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2433 d->coord_cache_.dump();
2438 void BufferView::insertLyXFile(FileName const & fname)
2440 LASSERT(d->cursor_.inTexted(), /**/);
2442 // Get absolute path of file and add ".lyx"
2443 // to the filename if necessary
2444 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2446 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2447 // emit message signal.
2448 message(bformat(_("Inserting document %1$s..."), disp_fn));
2451 Buffer buf("", false);
2452 if (buf.loadLyXFile(filename)) {
2453 ErrorList & el = buffer_.errorList("Parse");
2454 // Copy the inserted document error list into the current buffer one.
2455 el = buf.errorList("Parse");
2456 buffer_.undo().recordUndo(d->cursor_);
2457 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2458 buf.params().documentClassPtr(), el);
2459 res = _("Document %1$s inserted.");
2461 res = _("Could not insert document %1$s");
2464 buffer_.changed(true);
2465 // emit message signal.
2466 message(bformat(res, disp_fn));
2467 buffer_.errors("Parse");
2471 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2477 // Addup contribution of nested insets, from inside to outside,
2478 // keeping the outer paragraph for a special handling below
2479 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2480 CursorSlice const & sl = dit[i];
2484 // get relative position inside sl.inset()
2485 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2487 // Make relative position inside of the edited inset relative to sl.inset()
2491 // In case of an RTL inset, the edited inset will be positioned to the left
2494 bool boundary_i = boundary && i + 1 == dit.depth();
2495 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2500 // remember width for the case that sl.inset() is positioned in an RTL inset
2501 if (i && dit[i - 1].text()) {
2502 // If this Inset is inside a Text Inset, retrieve the Dimension
2503 // from the containing text instead of using Inset::dimension() which
2504 // might not be implemented.
2505 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2506 // elimination of Inset::dim_ cache. This coordOffset() method needs
2507 // to be rewritten in light of the new design.
2508 Dimension const & dim = parMetrics(dit[i - 1].text(),
2509 dit[i - 1].pit()).insetDimension(&sl.inset());
2512 Dimension const dim = sl.inset().dimension(*this);
2516 //lyxerr << "Cursor::getPos, i: "
2517 // << i << " x: " << xx << " y: " << y << endl;
2520 // Add contribution of initial rows of outermost paragraph
2521 CursorSlice const & sl = dit[0];
2522 TextMetrics const & tm = textMetrics(sl.text());
2523 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2524 LASSERT(!pm.rows().empty(), /**/);
2525 y -= pm.rows()[0].ascent();
2527 // FIXME: document this mess
2529 if (sl.pos() > 0 && dit.depth() == 1) {
2531 if (pos && boundary)
2533 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2534 rend = pm.pos2row(pos);
2536 rend = pm.pos2row(sl.pos());
2538 size_t rend = pm.pos2row(sl.pos());
2540 for (size_t rit = 0; rit != rend; ++rit)
2541 y += pm.rows()[rit].height();
2542 y += pm.rows()[rend].ascent();
2544 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2546 // Make relative position from the nested inset now bufferview absolute.
2547 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2550 // In the RTL case place the nested inset at the left of the cursor in
2551 // the outer paragraph
2552 bool boundary_1 = boundary && 1 == dit.depth();
2553 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2561 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2563 if (!paragraphVisible(dit))
2564 return Point(-1, -1);
2566 CursorSlice const & bot = dit.bottom();
2567 TextMetrics const & tm = textMetrics(bot.text());
2569 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2570 p.y_ += tm.parMetrics(bot.pit()).position();
2575 bool BufferView::paragraphVisible(DocIterator const & dit) const
2577 CursorSlice const & bot = dit.bottom();
2578 TextMetrics const & tm = textMetrics(bot.text());
2580 return tm.contains(bot.pit());
2584 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2586 Cursor const & cur = cursor();
2587 Font const font = cur.getFont();
2588 frontend::FontMetrics const & fm = theFontMetrics(font);
2589 int const asc = fm.maxAscent();
2590 int const des = fm.maxDescent();
2592 p = getPos(cur, cur.boundary());
2597 bool BufferView::cursorInView(Point const & p, int h) const
2599 Cursor const & cur = cursor();
2600 // does the cursor touch the screen ?
2601 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2607 void BufferView::draw(frontend::Painter & pain)
2609 if (height_ == 0 || width_ == 0)
2611 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2613 Text & text = buffer_.text();
2614 TextMetrics const & tm = d->text_metrics_[&text];
2615 int const y = tm.first().second->position();
2616 PainterInfo pi(this, pain);
2618 switch (d->update_strategy_) {
2620 case NoScreenUpdate:
2621 // If no screen painting is actually needed, only some the different
2622 // coordinates of insets and paragraphs needs to be updated.
2623 pi.full_repaint = true;
2624 pi.pain.setDrawingEnabled(false);
2628 case SingleParUpdate:
2629 pi.full_repaint = false;
2630 // In general, only the current row of the outermost paragraph
2631 // will be redrawn. Particular cases where selection spans
2632 // multiple paragraph are correctly detected in TextMetrics.
2636 case DecorationUpdate:
2637 // FIXME: We should also distinguish DecorationUpdate to avoid text
2638 // drawing if possible. This is not possible to do easily right now
2639 // because of the single backing pixmap.
2641 case FullScreenUpdate:
2642 // The whole screen, including insets, will be refreshed.
2643 pi.full_repaint = true;
2645 // Clear background.
2646 pain.fillRectangle(0, 0, width_, height_,
2647 pi.backgroundColor(&buffer_.inset()));
2652 // and possibly grey out below
2653 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2654 int const y2 = lastpm.second->position() + lastpm.second->descent();
2657 Color color = buffer().isInternal()
2658 ? Color_background : Color_bottomarea;
2659 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2663 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2665 // The scrollbar needs an update.
2668 // Normalize anchor for next time
2669 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2670 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2671 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2672 ParagraphMetrics const & pm = tm.parMetrics(pit);
2673 if (pm.position() + pm.descent() > 0) {
2674 d->anchor_pit_ = pit;
2675 d->anchor_ypos_ = pm.position();
2679 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2680 << " anchor ypos = " << d->anchor_ypos_);
2684 void BufferView::message(docstring const & msg)
2687 d->gui_->message(msg);
2691 void BufferView::showDialog(string const & name)
2694 d->gui_->showDialog(name, string());
2698 void BufferView::showDialog(string const & name,
2699 string const & data, Inset * inset)
2702 d->gui_->showDialog(name, data, inset);
2706 void BufferView::updateDialog(string const & name, string const & data)
2709 d->gui_->updateDialog(name, data);
2713 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2719 // FIXME: Move this out of BufferView again
2720 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2722 if (!fname.isReadableFile()) {
2723 docstring const error = from_ascii(strerror(errno));
2724 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2725 docstring const text =
2726 bformat(_("Could not read the specified document\n"
2727 "%1$s\ndue to the error: %2$s"), file, error);
2728 Alert::error(_("Could not read file"), text);
2732 if (!fname.isReadableFile()) {
2733 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2734 docstring const text =
2735 bformat(_("%1$s\n is not readable."), file);
2736 Alert::error(_("Could not open file"), text);
2740 // FIXME UNICODE: We don't know the encoding of the file
2741 docstring file_content = fname.fileContents("UTF-8");
2742 if (file_content.empty()) {
2743 Alert::error(_("Reading not UTF-8 encoded file"),
2744 _("The file is not UTF-8 encoded.\n"
2745 "It will be read as local 8Bit-encoded.\n"
2746 "If this does not give the correct result\n"
2747 "then please change the encoding of the file\n"
2748 "to UTF-8 with a program other than LyX.\n"));
2749 file_content = fname.fileContents("local8bit");
2752 return normalize_c(file_content);
2756 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2758 docstring const tmpstr = contentsOfPlaintextFile(f);
2763 Cursor & cur = cursor();
2764 cap::replaceSelection(cur);
2765 buffer_.undo().recordUndo(cur);
2767 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2769 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2771 buffer_.changed(true);
2775 docstring const & BufferView::inlineCompletion() const
2777 return d->inlineCompletion_;
2781 size_t const & BufferView::inlineCompletionUniqueChars() const
2783 return d->inlineCompletionUniqueChars_;
2787 DocIterator const & BufferView::inlineCompletionPos() const
2789 return d->inlineCompletionPos_;
2793 bool samePar(DocIterator const & a, DocIterator const & b)
2795 if (a.empty() && b.empty())
2797 if (a.empty() || b.empty())
2799 if (a.depth() != b.depth())
2801 return &a.innerParagraph() == &b.innerParagraph();
2805 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2806 docstring const & completion, size_t uniqueChars)
2808 uniqueChars = min(completion.size(), uniqueChars);
2809 bool changed = d->inlineCompletion_ != completion
2810 || d->inlineCompletionUniqueChars_ != uniqueChars;
2811 bool singlePar = true;
2812 d->inlineCompletion_ = completion;
2813 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2815 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2818 DocIterator const & old = d->inlineCompletionPos_;
2820 //lyxerr << "inlineCompletionPos changed" << std::endl;
2821 // old or pos are in another paragraph?
2822 if ((!samePar(cur, pos) && !pos.empty())
2823 || (!samePar(cur, old) && !old.empty())) {
2825 //lyxerr << "different paragraph" << std::endl;
2827 d->inlineCompletionPos_ = pos;
2832 if (singlePar && !(cur.disp_.update() & Update::Force))
2833 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2835 cur.updateFlags(cur.disp_.update() | Update::Force);