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), bookmark_edit_position_(0), gui_(0)
227 ScrollbarParameters scrollbarParameters_;
229 ScreenUpdateStrategy update_strategy_;
231 CoordCache coord_cache_;
233 /// Estimated average par height for scrollbar.
235 /// this is used to handle XSelection events in the right manner.
244 pit_type anchor_pit_;
248 vector<int> par_height_;
251 DocIterator inlineCompletionPos_;
253 docstring inlineCompletion_;
255 size_t inlineCompletionUniqueChars_;
257 /// keyboard mapping object.
260 /// last visited inset.
261 /** kept to send setMouseHover(false).
262 * Not owned, so don't delete.
266 // cache for id of the paragraph which was edited the last time
267 int bookmark_edit_position_;
269 mutable TextMetricsCache text_metrics_;
272 /** Not owned, so don't delete.
274 frontend::GuiBufferViewDelegate * gui_;
276 /// Cache for Find Next
277 FuncRequest search_request_cache_;
280 map<string, Inset *> edited_insets_;
284 BufferView::BufferView(Buffer & buf)
285 : width_(0), height_(0), full_screen_(false), buffer_(buf),
286 d(new Private(*this))
288 d->xsel_cache_.set = false;
289 d->intl_.initKeyMapper(lyxrc.use_kbmap);
291 d->cursor_.setBuffer(&buf);
292 d->cursor_.push(buffer_.inset());
293 d->cursor_.resetAnchor();
294 d->cursor_.setCurrentFont();
296 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
297 thePreviews().generateBufferPreviews(buffer_);
301 BufferView::~BufferView()
303 // current buffer is going to be switched-off, save cursor pos
304 // Ideally, the whole cursor stack should be saved, but session
305 // currently can only handle bottom (whole document) level pit and pos.
306 // That is to say, if a cursor is in a nested inset, it will be
307 // restore to the left of the top level inset.
308 LastFilePosSection::FilePos fp;
309 fp.pit = d->cursor_.bottom().pit();
310 fp.pos = d->cursor_.bottom().pos();
311 theSession().lastFilePos().save(buffer_.fileName(), fp);
317 int BufferView::rightMargin() const
319 // The additional test for the case the outliner is opened.
321 !lyxrc.full_screen_limit ||
322 width_ < lyxrc.full_screen_width + 20)
325 return (width_ - lyxrc.full_screen_width) / 2;
329 int BufferView::leftMargin() const
331 return rightMargin();
335 bool BufferView::isTopScreen() const
337 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
341 bool BufferView::isBottomScreen() const
343 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
347 Intl & BufferView::getIntl()
353 Intl const & BufferView::getIntl() const
359 CoordCache & BufferView::coordCache()
361 return d->coord_cache_;
365 CoordCache const & BufferView::coordCache() const
367 return d->coord_cache_;
371 Buffer & BufferView::buffer()
377 Buffer const & BufferView::buffer() const
383 bool BufferView::fitCursor()
385 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
386 frontend::FontMetrics const & fm =
387 theFontMetrics(d->cursor_.getFont().fontInfo());
388 int const asc = fm.maxAscent();
389 int const des = fm.maxDescent();
390 Point const p = getPos(d->cursor_, d->cursor_.boundary());
391 if (p.y_ - asc >= 0 && p.y_ + des < height_)
398 void BufferView::processUpdateFlags(Update::flags flags)
400 // last_inset_ points to the last visited inset. This pointer may become
401 // invalid because of keyboard editing. Since all such operations
402 // causes screen update(), I reset last_inset_ to avoid such a problem.
404 // This is close to a hot-path.
405 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
406 << "[fitcursor = " << (flags & Update::FitCursor)
407 << ", forceupdate = " << (flags & Update::Force)
408 << ", singlepar = " << (flags & Update::SinglePar)
409 << "] buffer: " << &buffer_);
411 buffer_.updateMacros();
413 // Now do the first drawing step if needed. This consists on updating
414 // the CoordCache in updateMetrics().
415 // The second drawing step is done in WorkArea::redraw() if needed.
417 // Case when no explicit update is requested.
419 // no need to redraw anything.
420 d->update_strategy_ = NoScreenUpdate;
424 if (flags == Update::Decoration) {
425 d->update_strategy_ = DecorationUpdate;
426 buffer_.changed(false);
430 if (flags == Update::FitCursor
431 || flags == (Update::Decoration | Update::FitCursor)) {
432 // tell the frontend to update the screen if needed.
437 if (flags & Update::Decoration) {
438 d->update_strategy_ = DecorationUpdate;
439 buffer_.changed(false);
442 // no screen update is needed.
443 d->update_strategy_ = NoScreenUpdate;
447 bool const full_metrics = flags & Update::Force || !singleParUpdate();
450 // We have to update the full screen metrics.
453 if (!(flags & Update::FitCursor)) {
454 // Nothing to do anymore. Trigger a redraw and return
455 buffer_.changed(false);
459 // updateMetrics() does not update paragraph position
460 // This is done at draw() time. So we need a redraw!
461 buffer_.changed(false);
464 // The cursor is off screen so ensure it is visible.
471 void BufferView::updateScrollbar()
473 if (height_ == 0 && width_ == 0)
476 // We prefer fixed size line scrolling.
477 d->scrollbarParameters_.single_step = defaultRowHeight();
478 // We prefer full screen page scrolling.
479 d->scrollbarParameters_.page_step = height_;
481 Text & t = buffer_.text();
482 TextMetrics & tm = d->text_metrics_[&t];
484 LYXERR(Debug::GUI, " Updating scrollbar: height: "
485 << t.paragraphs().size()
486 << " curr par: " << d->cursor_.bottom().pit()
487 << " default height " << defaultRowHeight());
489 size_t const parsize = t.paragraphs().size();
490 if (d->par_height_.size() != parsize) {
491 d->par_height_.clear();
492 // FIXME: We assume a default paragraph height of 2 rows. This
493 // should probably be pondered with the screen width.
494 d->par_height_.resize(parsize, defaultRowHeight() * 2);
497 // Look at paragraph heights on-screen
498 pair<pit_type, ParagraphMetrics const *> first = tm.first();
499 pair<pit_type, ParagraphMetrics const *> last = tm.last();
500 for (pit_type pit = first.first; pit <= last.first; ++pit) {
501 d->par_height_[pit] = tm.parMetrics(pit).height();
502 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
503 << d->par_height_[pit]);
506 int top_pos = first.second->position() - first.second->ascent();
507 int bottom_pos = last.second->position() + last.second->descent();
508 bool first_visible = first.first == 0 && top_pos >= 0;
509 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
510 if (first_visible && last_visible) {
511 d->scrollbarParameters_.min = 0;
512 d->scrollbarParameters_.max = 0;
516 d->scrollbarParameters_.min = top_pos;
517 for (size_t i = 0; i != size_t(first.first); ++i)
518 d->scrollbarParameters_.min -= d->par_height_[i];
519 d->scrollbarParameters_.max = bottom_pos;
520 for (size_t i = last.first + 1; i != parsize; ++i)
521 d->scrollbarParameters_.max += d->par_height_[i];
523 d->scrollbarParameters_.position = 0;
524 // The reference is the top position so we remove one page.
525 if (lyxrc.scroll_below_document)
526 d->scrollbarParameters_.max -= minVisiblePart();
528 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
532 ScrollbarParameters const & BufferView::scrollbarParameters() const
534 return d->scrollbarParameters_;
538 docstring BufferView::toolTip(int x, int y) const
540 // Get inset under mouse, if there is one.
541 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
543 // No inset, no tooltip...
545 return covering_inset->toolTip(*this, x, y);
549 docstring BufferView::contextMenu(int x, int y) const
551 //If there is a selection, return the containing inset menu
552 if (d->cursor_.selection())
553 return d->cursor_.inset().contextMenu(*this, x, y);
555 // Get inset under mouse, if there is one.
556 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
558 return covering_inset->contextMenu(*this, x, y);
560 return buffer_.inset().contextMenu(*this, x, y);
564 void BufferView::scrollDocView(int value)
566 int const offset = value - d->scrollbarParameters_.position;
568 // No scrolling at all? No need to redraw anything
572 // If the offset is less than 2 screen height, prefer to scroll instead.
573 if (abs(offset) <= 2 * height_) {
574 d->anchor_ypos_ -= offset;
575 buffer_.changed(true);
579 // cut off at the top
580 if (value <= d->scrollbarParameters_.min) {
581 DocIterator dit = doc_iterator_begin(&buffer_);
583 LYXERR(Debug::SCROLLING, "scroll to top");
587 // cut off at the bottom
588 if (value >= d->scrollbarParameters_.max) {
589 DocIterator dit = doc_iterator_end(&buffer_);
592 LYXERR(Debug::SCROLLING, "scroll to bottom");
596 // find paragraph at target position
597 int par_pos = d->scrollbarParameters_.min;
599 for (; i != int(d->par_height_.size()); ++i) {
600 par_pos += d->par_height_[i];
601 if (par_pos >= value)
605 if (par_pos < value) {
606 // It seems we didn't find the correct pit so stay on the safe side and
608 LYXERR0("scrolling position not found!");
609 scrollDocView(d->scrollbarParameters_.max);
613 DocIterator dit = doc_iterator_begin(&buffer_);
615 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
620 // FIXME: this method is not working well.
621 void BufferView::setCursorFromScrollbar()
623 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
625 int const height = 2 * defaultRowHeight();
626 int const first = height;
627 int const last = height_ - height;
629 Cursor const & oldcur = d->cursor_;
631 switch (cursorStatus(oldcur)) {
639 int const y = getPos(oldcur, oldcur.boundary()).y_;
640 newy = min(last, max(y, first));
644 // We reset the cursor because cursorStatus() does not
645 // work when the cursor is within mathed.
648 tm.setCursorFromCoordinates(cur, 0, newy);
650 // update the bufferview cursor and notify insets
651 // FIXME: Care about the d->cursor_ flags to redraw if needed
652 Cursor old = d->cursor_;
654 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
656 d->cursor_.fixIfBroken();
660 Change const BufferView::getCurrentChange() const
662 if (!d->cursor_.selection())
663 return Change(Change::UNCHANGED);
665 DocIterator dit = d->cursor_.selectionBegin();
666 return dit.paragraph().lookupChange(dit.pos());
670 // this could be used elsewhere as well?
671 // FIXME: This does not work within mathed!
672 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
674 Point const p = getPos(dit, dit.boundary());
677 if (p.y_ > workHeight())
683 void BufferView::bookmarkEditPosition()
685 // Don't eat cpu time for each keystroke
686 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
689 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
693 void BufferView::saveBookmark(unsigned int idx)
695 // tentatively save bookmark, id and pos will be used to
696 // acturately locate a bookmark in a 'live' lyx session.
697 // pit and pos will be updated with bottom level pit/pos
699 if (!buffer_.isInternal()) {
700 theSession().bookmarks().save(
702 d->cursor_.bottom().pit(),
703 d->cursor_.bottom().pos(),
704 d->cursor_.paragraph().id(),
709 // emit message signal.
710 message(_("Save bookmark"));
715 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
716 int top_id, pos_type top_pos)
718 bool success = false;
721 d->cursor_.clearSelection();
723 // if a valid par_id is given, try it first
724 // This is the case for a 'live' bookmark when unique paragraph ID
725 // is used to track bookmarks.
727 dit = buffer_.getParFromID(top_id);
729 dit.pos() = min(dit.paragraph().size(), top_pos);
730 // Some slices of the iterator may not be
731 // reachable (e.g. closed collapsable inset)
732 // so the dociterator may need to be
733 // shortened. Otherwise, setCursor may crash
734 // lyx when the cursor can not be set to these
736 size_t const n = dit.depth();
737 for (size_t i = 0; i < n; ++i)
738 if (!dit[i].inset().editable()) {
746 // if top_id == 0, or searching through top_id failed
747 // This is the case for a 'restored' bookmark when only bottom
748 // (document level) pit was saved. Because of this, bookmark
749 // restoration is inaccurate. If a bookmark was within an inset,
750 // it will be restored to the left of the outmost inset that contains
752 if (bottom_pit < int(buffer_.paragraphs().size())) {
753 dit = doc_iterator_begin(&buffer_);
755 dit.pit() = bottom_pit;
756 dit.pos() = min(bottom_pos, dit.paragraph().size());
761 // Note: only bottom (document) level pit is set.
763 // set the current font.
764 d->cursor_.setCurrentFont();
765 // To center the screen on this new position we need the
766 // paragraph position which is computed at draw() time.
767 // So we need a redraw!
768 buffer_.changed(false);
777 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
779 if (lyxrc.rtl_support) {
780 if (d->cursor_.real_current_font.isRightToLeft()) {
781 if (d->intl_.keymap == Intl::PRIMARY)
782 d->intl_.keyMapSec();
784 if (d->intl_.keymap == Intl::SECONDARY)
785 d->intl_.keyMapPrim();
789 d->intl_.getTransManager().translateAndInsert(c, t, cur);
793 int BufferView::workWidth() const
799 void BufferView::recenter()
801 showCursor(d->cursor_, true);
805 void BufferView::showCursor()
807 showCursor(d->cursor_, false);
811 void BufferView::showCursor(DocIterator const & dit, bool recenter)
813 if (scrollToCursor(dit, recenter))
814 buffer_.changed(false);
818 void BufferView::scrollToCursor()
820 scrollToCursor(d->cursor_, false);
824 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
826 // We are not properly started yet, delay until resizing is
831 LYXERR(Debug::SCROLLING, "recentering!");
833 CursorSlice const & bot = dit.bottom();
834 TextMetrics & tm = d->text_metrics_[bot.text()];
836 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
837 int bot_pit = bot.pit();
838 if (bot_pit > max_pit) {
839 // FIXME: Why does this happen?
840 LYXERR0("bottom pit is greater that max pit: "
841 << bot_pit << " > " << max_pit);
845 if (bot_pit == tm.first().first - 1)
846 tm.newParMetricsUp();
847 else if (bot_pit == tm.last().first + 1)
848 tm.newParMetricsDown();
850 if (tm.contains(bot_pit)) {
851 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
852 LASSERT(!pm.rows().empty(), /**/);
853 // FIXME: smooth scrolling doesn't work in mathed.
854 CursorSlice const & cs = dit.innerTextSlice();
855 int offset = coordOffset(dit, dit.boundary()).y_;
856 int ypos = pm.position() + offset;
857 Dimension const & row_dim =
858 pm.getRow(cs.pos(), dit.boundary()).dimension();
861 scrolled = scroll(ypos - height_/2);
862 else if (ypos - row_dim.ascent() < 0)
863 scrolled = scrollUp(- ypos + row_dim.ascent());
864 else if (ypos + row_dim.descent() > height_)
865 scrolled = scrollDown(ypos - height_ + defaultRowHeight() );
867 // else, nothing to do, the cursor is already visible so we just return.
875 // fix inline completion position
876 if (d->inlineCompletionPos_.fixIfBroken())
877 d->inlineCompletionPos_ = DocIterator();
879 tm.redoParagraph(bot_pit);
880 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
881 int offset = coordOffset(dit, dit.boundary()).y_;
883 d->anchor_pit_ = bot_pit;
884 CursorSlice const & cs = dit.innerTextSlice();
885 Dimension const & row_dim =
886 pm.getRow(cs.pos(), dit.boundary()).dimension();
889 d->anchor_ypos_ = height_/2;
890 else if (d->anchor_pit_ == 0)
891 d->anchor_ypos_ = offset + pm.ascent();
892 else if (d->anchor_pit_ == max_pit)
893 d->anchor_ypos_ = height_ - offset - row_dim.descent();
894 else if (offset > height_)
895 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
897 d->anchor_ypos_ = defaultRowHeight() * 2;
904 void BufferView::updateDocumentClass(DocumentClass const * const olddc)
906 message(_("Converting document to new document class..."));
908 StableDocIterator backcur(d->cursor_);
909 ErrorList & el = buffer_.errorList("Class Switch");
910 cap::switchBetweenClasses(
911 olddc, buffer_.params().documentClassPtr(),
912 static_cast<InsetText &>(buffer_.inset()), el);
914 setCursor(backcur.asDocIterator(&buffer_));
916 buffer_.errors("Class Switch");
917 buffer_.updateBuffer();
920 /** Return the change status at cursor position, taking in account the
921 * status at each level of the document iterator (a table in a deleted
922 * footnote is deleted).
923 * When \param outer is true, the top slice is not looked at.
925 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
927 size_t const depth = dit.depth() - (outer ? 1 : 0);
929 for (size_t i = 0 ; i < depth ; ++i) {
930 CursorSlice const & slice = dit[i];
931 if (!slice.inset().inMathed()
932 && slice.pos() < slice.paragraph().size()) {
933 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
934 if (ch != Change::UNCHANGED)
938 return Change::UNCHANGED;
942 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
944 // Can we use a readonly buffer?
945 if (buffer_.isReadonly()
946 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
947 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
948 flag.message(from_utf8(N_("Document is read-only")));
949 flag.setEnabled(false);
952 // Are we in a DELETED change-tracking region?
953 if (lookupChangeType(d->cursor_, true) == Change::DELETED
954 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
955 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
956 flag.message(from_utf8(N_("This portion of the document is deleted.")));
957 flag.setEnabled(false);
961 Cursor & cur = d->cursor_;
963 if (cur.getStatus(cmd, flag))
966 switch (cmd.action) {
968 // FIXME: This is a bit problematic because we don't check is this is a
969 // document BufferView or not for these LFUNs. We probably have to
970 // dispatch both to currentBufferView() and, if that fails,
971 // to documentBufferView(); same as we do know for current Buffer and
972 // document Buffer. Ideally those LFUN should go to Buffer as they*
973 // operate on the full Buffer and the cursor is only needed either for
974 // an Undo record or to restore a cursor position. But we don't know
975 // how to do that inside Buffer of course.
976 case LFUN_BUFFER_PARAMS_APPLY:
977 case LFUN_LAYOUT_MODULES_CLEAR:
978 case LFUN_LAYOUT_MODULE_ADD:
979 case LFUN_LAYOUT_RELOAD:
980 case LFUN_TEXTCLASS_APPLY:
981 case LFUN_TEXTCLASS_LOAD:
982 flag.setEnabled(!buffer_.isReadonly());
986 flag.setEnabled(buffer_.undo().hasUndoStack());
989 flag.setEnabled(buffer_.undo().hasRedoStack());
991 case LFUN_FILE_INSERT:
992 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
993 case LFUN_FILE_INSERT_PLAINTEXT:
994 case LFUN_BOOKMARK_SAVE:
995 // FIXME: Actually, these LFUNS should be moved to Text
996 flag.setEnabled(cur.inTexted());
999 case LFUN_FONT_STATE:
1000 case LFUN_LABEL_INSERT:
1001 case LFUN_INFO_INSERT:
1002 case LFUN_INSET_EDIT:
1003 case LFUN_PARAGRAPH_GOTO:
1004 case LFUN_NOTE_NEXT:
1005 case LFUN_REFERENCE_NEXT:
1006 case LFUN_WORD_FIND:
1007 case LFUN_WORD_FIND_FORWARD:
1008 case LFUN_WORD_FIND_BACKWARD:
1009 case LFUN_WORD_FINDADV:
1010 case LFUN_WORD_REPLACE:
1013 case LFUN_MARK_TOGGLE:
1014 case LFUN_SCREEN_RECENTER:
1015 case LFUN_SCREEN_SHOW_CURSOR:
1016 case LFUN_BIBTEX_DATABASE_ADD:
1017 case LFUN_BIBTEX_DATABASE_DEL:
1018 case LFUN_ALL_INSETS_TOGGLE:
1019 case LFUN_STATISTICS:
1020 case LFUN_BRANCH_ADD_INSERT:
1021 case LFUN_KEYMAP_OFF:
1022 case LFUN_KEYMAP_PRIMARY:
1023 case LFUN_KEYMAP_SECONDARY:
1024 case LFUN_KEYMAP_TOGGLE:
1025 flag.setEnabled(true);
1028 case LFUN_LABEL_COPY_AS_REF: {
1029 // if there is an inset at cursor, see whether it
1031 Inset * inset = cur.nextInset();
1032 if (!inset || !inset->getStatus(cur, cmd, flag))
1033 flag.setEnabled(false);
1037 case LFUN_LABEL_GOTO: {
1038 flag.setEnabled(!cmd.argument().empty()
1039 || getInsetByCode<InsetRef>(cur, REF_CODE));
1043 case LFUN_CHANGES_TRACK:
1044 flag.setEnabled(true);
1045 flag.setOnOff(buffer_.params().trackChanges);
1048 case LFUN_CHANGES_OUTPUT:
1049 flag.setEnabled(true);
1050 flag.setOnOff(buffer_.params().outputChanges);
1053 case LFUN_CHANGES_MERGE:
1054 case LFUN_CHANGE_NEXT:
1055 case LFUN_CHANGE_PREVIOUS:
1056 case LFUN_ALL_CHANGES_ACCEPT:
1057 case LFUN_ALL_CHANGES_REJECT:
1058 // TODO: context-sensitive enabling of LFUNs
1059 // In principle, these command should only be enabled if there
1060 // is a change in the document. However, without proper
1061 // optimizations, this will inevitably result in poor performance.
1062 flag.setEnabled(true);
1065 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1066 flag.setOnOff(buffer_.params().compressed);
1070 case LFUN_SCREEN_UP:
1071 case LFUN_SCREEN_DOWN:
1073 case LFUN_SCREEN_UP_SELECT:
1074 case LFUN_SCREEN_DOWN_SELECT:
1075 case LFUN_INSET_FORALL:
1076 flag.setEnabled(true);
1079 case LFUN_LAYOUT_TABULAR:
1080 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1084 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1087 case LFUN_LAYOUT_PARAGRAPH:
1088 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1091 case LFUN_DIALOG_SHOW_NEW_INSET:
1092 // FIXME: this is wrong, but I do not understand the
1094 if (cur.inset().lyxCode() == CAPTION_CODE)
1095 return cur.inset().getStatus(cur, cmd, flag);
1096 // FIXME we should consider passthru paragraphs too.
1097 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1100 case LFUN_CITATION_INSERT: {
1101 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1102 // FIXME: This could turn in a recursive hell.
1103 // Shouldn't we use Buffer::getStatus() instead?
1104 flag.setEnabled(lyx::getStatus(fr).enabled());
1107 case LFUN_INSET_APPLY: {
1108 string const name = cmd.getArg(0);
1109 Inset * inset = editedInset(name);
1111 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1113 if (!inset->getStatus(cur, fr, fs)) {
1114 // Every inset is supposed to handle this
1115 LASSERT(false, break);
1119 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1120 flag |= lyx::getStatus(fr);
1126 flag.setEnabled(false);
1134 Inset * BufferView::editedInset(string const & name) const
1136 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1137 return it == d->edited_insets_.end() ? 0 : it->second;
1141 void BufferView::editInset(string const & name, Inset * inset)
1143 d->edited_insets_[name] = inset;
1147 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1149 //lyxerr << [ cmd = " << cmd << "]" << endl;
1151 // Make sure that the cached BufferView is correct.
1152 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1153 << " arg[" << to_utf8(cmd.argument()) << ']'
1154 << " x[" << cmd.x << ']'
1155 << " y[" << cmd.y << ']'
1156 << " button[" << cmd.button() << ']');
1158 string const argument = to_utf8(cmd.argument());
1159 Cursor & cur = d->cursor_;
1161 // Don't dispatch function that does not apply to internal buffers.
1162 if (buffer_.isInternal()
1163 && lyxaction.funcHasFlag(cmd.action, LyXAction::NoInternal))
1166 // We'll set this back to false if need be.
1167 bool dispatched = true;
1168 buffer_.undo().beginUndoGroup();
1170 switch (cmd.action) {
1172 case LFUN_BUFFER_PARAMS_APPLY: {
1173 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1174 cur.recordUndoFullDocument();
1175 istringstream ss(to_utf8(cmd.argument()));
1178 int const unknown_tokens = buffer_.readHeader(lex);
1179 if (unknown_tokens != 0) {
1180 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1181 << unknown_tokens << " unknown token"
1182 << (unknown_tokens == 1 ? "" : "s"));
1184 updateDocumentClass(oldClass);
1186 // We are most certainly here because of a change in the document
1187 // It is then better to make sure that all dialogs are in sync with
1188 // current document settings.
1189 dr.update(Update::Force | Update::FitCursor);
1193 case LFUN_LAYOUT_MODULES_CLEAR: {
1194 DocumentClass const * const oldClass =
1195 buffer_.params().documentClassPtr();
1196 cur.recordUndoFullDocument();
1197 buffer_.params().clearLayoutModules();
1198 buffer_.params().makeDocumentClass();
1199 updateDocumentClass(oldClass);
1200 dr.update(Update::Force | Update::FitCursor);
1204 case LFUN_LAYOUT_MODULE_ADD: {
1205 BufferParams const & params = buffer_.params();
1206 if (!params.moduleCanBeAdded(argument)) {
1207 LYXERR0("Module `" << argument <<
1208 "' cannot be added due to failed requirements or "
1209 "conflicts with installed modules.");
1212 DocumentClass const * const oldClass = params.documentClassPtr();
1213 cur.recordUndoFullDocument();
1214 buffer_.params().addLayoutModule(argument);
1215 buffer_.params().makeDocumentClass();
1216 updateDocumentClass(oldClass);
1217 dr.update(Update::Force | Update::FitCursor);
1221 case LFUN_TEXTCLASS_APPLY: {
1222 if (!LayoutFileList::get().load(argument, buffer_.temppath()) &&
1223 !LayoutFileList::get().load(argument, buffer_.filePath()))
1226 LayoutFile const * old_layout = buffer_.params().baseClass();
1227 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1229 if (old_layout == new_layout)
1233 //Save the old, possibly modular, layout for use in conversion.
1234 DocumentClass const * const oldDocClass =
1235 buffer_.params().documentClassPtr();
1236 cur.recordUndoFullDocument();
1237 buffer_.params().setBaseClass(argument);
1238 buffer_.params().makeDocumentClass();
1239 updateDocumentClass(oldDocClass);
1240 dr.update(Update::Force | Update::FitCursor);
1244 case LFUN_TEXTCLASS_LOAD:
1245 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1246 LayoutFileList::get().load(argument, buffer_.filePath());
1249 case LFUN_LAYOUT_RELOAD: {
1250 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1251 LayoutFileIndex bc = buffer_.params().baseClassID();
1252 LayoutFileList::get().reset(bc);
1253 buffer_.params().setBaseClass(bc);
1254 buffer_.params().makeDocumentClass();
1255 updateDocumentClass(oldClass);
1256 dr.update(Update::Force | Update::FitCursor);
1261 dr.setMessage(_("Undo"));
1262 cur.clearSelection();
1263 if (!cur.textUndo())
1264 dr.setMessage(_("No further undo information"));
1266 dr.update(Update::Force | Update::FitCursor);
1270 dr.setMessage(_("Redo"));
1271 cur.clearSelection();
1272 if (!cur.textRedo())
1273 dr.setMessage(_("No further redo information"));
1275 dr.update(Update::Force | Update::FitCursor);
1278 case LFUN_FONT_STATE:
1279 dr.setMessage(cur.currentState());
1282 case LFUN_BOOKMARK_SAVE:
1283 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1286 case LFUN_LABEL_GOTO: {
1287 docstring label = cmd.argument();
1288 if (label.empty()) {
1290 getInsetByCode<InsetRef>(cur, REF_CODE);
1292 label = inset->getParam("reference");
1293 // persistent=false: use temp_bookmark
1302 case LFUN_INSET_EDIT: {
1303 FuncRequest fr(cmd);
1304 // if there is an inset at cursor, see whether it
1306 Inset * inset = cur.nextInset();
1308 inset->dispatch(cur, fr);
1309 // if it did not work, try the underlying inset.
1310 if (!inset || !cur.result().dispatched())
1313 // FIXME I'm adding the last break to solve a crash,
1314 // but that is obviously not right.
1315 if (!cur.result().dispatched())
1316 // It did not work too; no action needed.
1321 case LFUN_PARAGRAPH_GOTO: {
1322 int const id = convert<int>(cmd.getArg(0));
1323 int const pos = convert<int>(cmd.getArg(1));
1325 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1326 b = theBufferList().next(b)) {
1328 DocIterator dit = b->getParFromID(id);
1330 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1334 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1335 << " found in buffer `"
1336 << b->absFileName() << "'.");
1338 if (b == &buffer_) {
1342 dr.update(Update::Force | Update::FitCursor);
1344 // Switch to other buffer view and resend cmd
1345 lyx::dispatch(FuncRequest(
1346 LFUN_BUFFER_SWITCH, b->absFileName()));
1354 case LFUN_NOTE_NEXT:
1355 gotoInset(this, NOTE_CODE, false);
1358 case LFUN_REFERENCE_NEXT: {
1359 vector<InsetCode> tmp;
1360 tmp.push_back(LABEL_CODE);
1361 tmp.push_back(REF_CODE);
1362 gotoInset(this, tmp, true);
1366 case LFUN_CHANGES_TRACK:
1367 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1370 case LFUN_CHANGES_OUTPUT:
1371 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1372 if (buffer_.params().outputChanges) {
1373 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1374 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1375 LaTeXFeatures::isAvailable("xcolor");
1377 if (!dvipost && !xcolorulem) {
1378 Alert::warning(_("Changes not shown in LaTeX output"),
1379 _("Changes will not be highlighted in LaTeX output, "
1380 "because neither dvipost nor xcolor/ulem are installed.\n"
1381 "Please install these packages or redefine "
1382 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1383 } else if (!xcolorulem) {
1384 Alert::warning(_("Changes not shown in LaTeX output"),
1385 _("Changes will not be highlighted in LaTeX output "
1386 "when using pdflatex, because xcolor and ulem are not installed.\n"
1387 "Please install both packages or redefine "
1388 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1393 case LFUN_CHANGE_NEXT:
1394 findNextChange(this);
1395 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1396 dr.update(Update::Force | Update::FitCursor);
1399 case LFUN_CHANGE_PREVIOUS:
1400 findPreviousChange(this);
1401 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1402 dr.update(Update::Force | Update::FitCursor);
1405 case LFUN_CHANGES_MERGE:
1406 if (findNextChange(this) || findPreviousChange(this)) {
1407 dr.update(Update::Force | Update::FitCursor);
1408 showDialog("changes");
1412 case LFUN_ALL_CHANGES_ACCEPT:
1413 // select complete document
1415 cur.selHandle(true);
1416 buffer_.text().cursorBottom(cur);
1417 // accept everything in a single step to support atomic undo
1418 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1419 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1420 dr.update(Update::Force | Update::FitCursor);
1423 case LFUN_ALL_CHANGES_REJECT:
1424 // select complete document
1426 cur.selHandle(true);
1427 buffer_.text().cursorBottom(cur);
1428 // reject everything in a single step to support atomic undo
1429 // Note: reject does not work recursively; the user may have to repeat the operation
1430 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1431 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1432 dr.update(Update::Force | Update::FitCursor);
1435 case LFUN_WORD_FIND_FORWARD:
1436 case LFUN_WORD_FIND_BACKWARD: {
1437 static docstring last_search;
1438 docstring searched_string;
1440 if (!cmd.argument().empty()) {
1441 last_search = cmd.argument();
1442 searched_string = cmd.argument();
1444 searched_string = last_search;
1447 if (searched_string.empty())
1450 bool const fw = cmd.action == LFUN_WORD_FIND_FORWARD;
1451 docstring const data =
1452 find2string(searched_string, true, false, fw);
1453 find(this, FuncRequest(LFUN_WORD_FIND, data));
1457 case LFUN_WORD_FIND: {
1458 FuncRequest req = cmd;
1459 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1460 req = d->search_request_cache_;
1461 if (req.argument().empty()) {
1462 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1465 if (find(this, req))
1468 message(_("String not found!"));
1469 d->search_request_cache_ = req;
1473 case LFUN_WORD_REPLACE: {
1474 bool has_deleted = false;
1475 if (cur.selection()) {
1476 DocIterator beg = cur.selectionBegin();
1477 DocIterator end = cur.selectionEnd();
1478 if (beg.pit() == end.pit()) {
1479 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1481 && cur.paragraph().isDeleted(p))
1486 replace(this, cmd, has_deleted);
1490 case LFUN_WORD_FINDADV: {
1491 FindAndReplaceOptions opt;
1492 istringstream iss(to_utf8(cmd.argument()));
1494 if (findAdv(this, opt))
1502 cur.clearSelection();
1503 dr.setMessage(from_utf8(N_("Mark off")));
1507 cur.clearSelection();
1509 dr.setMessage(from_utf8(N_("Mark on")));
1512 case LFUN_MARK_TOGGLE:
1513 cur.setSelection(false);
1516 dr.setMessage(from_utf8(N_("Mark removed")));
1519 dr.setMessage(from_utf8(N_("Mark set")));
1524 case LFUN_SCREEN_SHOW_CURSOR:
1528 case LFUN_SCREEN_RECENTER:
1532 case LFUN_BIBTEX_DATABASE_ADD: {
1533 Cursor tmpcur = cur;
1534 findInset(tmpcur, BIBTEX_CODE, false);
1535 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1538 if (inset->addDatabase(cmd.argument()))
1539 buffer_.updateBibfilesCache();
1544 case LFUN_BIBTEX_DATABASE_DEL: {
1545 Cursor tmpcur = cur;
1546 findInset(tmpcur, BIBTEX_CODE, false);
1547 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1550 if (inset->delDatabase(cmd.argument()))
1551 buffer_.updateBibfilesCache();
1556 case LFUN_STATISTICS: {
1557 DocIterator from, to;
1558 if (cur.selection()) {
1559 from = cur.selectionBegin();
1560 to = cur.selectionEnd();
1562 from = doc_iterator_begin(&buffer_);
1563 to = doc_iterator_end(&buffer_);
1565 int const words = countWords(from, to);
1566 int const chars = countChars(from, to, false);
1567 int const chars_blanks = countChars(from, to, true);
1569 if (cur.selection())
1570 message = _("Statistics for the selection:");
1572 message = _("Statistics for the document:");
1575 message += bformat(_("%1$d words"), words);
1577 message += _("One word");
1579 if (chars_blanks != 1)
1580 message += bformat(_("%1$d characters (including blanks)"),
1583 message += _("One character (including blanks)");
1586 message += bformat(_("%1$d characters (excluding blanks)"),
1589 message += _("One character (excluding blanks)");
1591 Alert::information(_("Statistics"), message);
1595 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1596 // turn compression on/off
1597 buffer_.params().compressed = !buffer_.params().compressed;
1600 case LFUN_LABEL_COPY_AS_REF: {
1601 // if there is an inset at cursor, try to copy it
1602 Inset * inset = &cur.inset();
1603 if (!inset || !inset->asInsetMath())
1604 inset = cur.nextInset();
1606 FuncRequest tmpcmd = cmd;
1607 inset->dispatch(cur, tmpcmd);
1609 if (!cur.result().dispatched())
1610 // It did not work too; no action needed.
1612 cur.clearSelection();
1613 dr.update(Update::SinglePar | Update::FitCursor);
1617 case LFUN_SCREEN_UP:
1618 case LFUN_SCREEN_DOWN: {
1619 Point p = getPos(cur, cur.boundary());
1620 // This code has been commented out to enable to scroll down a
1621 // document, even if there are large insets in it (see bug #5465).
1622 /*if (p.y_ < 0 || p.y_ > height_) {
1623 // The cursor is off-screen so recenter before proceeding.
1625 p = getPos(cur, cur.boundary());
1627 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1628 ? -height_ : height_);
1629 if (cmd.action == LFUN_SCREEN_UP && scrolled > -height_)
1631 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1632 p = Point(width_, height_);
1634 bool const in_texted = cur.inTexted();
1636 buffer_.changed(true);
1637 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1638 true, cmd.action == LFUN_SCREEN_UP);
1639 //FIXME: what to do with cur.x_target()?
1640 bool update = in_texted && cur.bv().checkDepm(cur, old);
1643 dr.update(Update::Force | Update::FitCursor);
1651 case LFUN_SCREEN_UP_SELECT: {
1652 cur.selHandle(true);
1653 if (isTopScreen()) {
1654 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1658 int y = getPos(cur, cur.boundary()).y_;
1659 int const ymin = y - height_ + defaultRowHeight();
1660 while (y > ymin && cur.up())
1661 y = getPos(cur, cur.boundary()).y_;
1664 dr.update(Update::SinglePar | Update::FitCursor);
1668 case LFUN_SCREEN_DOWN_SELECT: {
1669 cur.selHandle(true);
1670 if (isBottomScreen()) {
1671 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1675 int y = getPos(cur, cur.boundary()).y_;
1676 int const ymax = y + height_ - defaultRowHeight();
1677 while (y < ymax && cur.down())
1678 y = getPos(cur, cur.boundary()).y_;
1681 dr.update(Update::SinglePar | Update::FitCursor);
1686 // This would be in Buffer class if only Cursor did not
1687 // require a bufferview
1688 case LFUN_INSET_FORALL: {
1689 docstring const name = from_utf8(cmd.getArg(0));
1690 string const commandstr = cmd.getLongArg(1);
1691 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1693 // an arbitrary number to limit number of iterations
1694 const int max_iter = 10000;
1696 Cursor & cur = d->cursor_;
1697 Cursor const savecur = cur;
1699 if (!cur.nextInset())
1701 cur.beginUndoGroup();
1702 while(cur && iterations < max_iter) {
1703 Inset * ins = cur.nextInset();
1706 docstring insname = ins->name();
1707 while (!insname.empty()) {
1708 if (insname == name || name == from_utf8("*")) {
1714 size_t const i = insname.rfind(':');
1715 if (i == string::npos)
1717 insname = insname.substr(0, i);
1724 dr.update(Update::Force);
1726 if (iterations >= max_iter) {
1728 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1730 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1735 case LFUN_ALL_INSETS_TOGGLE: {
1737 string const name = split(to_utf8(cmd.argument()), action, ' ');
1738 InsetCode const inset_code = insetCode(name);
1740 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1742 Inset & inset = cur.buffer()->inset();
1743 InsetIterator it = inset_iterator_begin(inset);
1744 InsetIterator const end = inset_iterator_end(inset);
1745 for (; it != end; ++it) {
1746 if (it->asInsetCollapsable()
1747 && (inset_code == NO_CODE
1748 || inset_code == it->lyxCode())) {
1749 Cursor tmpcur = cur;
1750 tmpcur.pushBackward(*it);
1751 it->dispatch(tmpcur, fr);
1754 dr.update(Update::Force | Update::FitCursor);
1758 case LFUN_BRANCH_ADD_INSERT: {
1759 docstring branch_name = from_utf8(cmd.getArg(0));
1760 if (branch_name.empty())
1761 if (!Alert::askForText(branch_name, _("Branch name")) ||
1762 branch_name.empty())
1765 DispatchResult drtmp;
1766 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1767 if (drtmp.error()) {
1768 Alert::warning(_("Branch already exists"), drtmp.message());
1771 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1775 case LFUN_KEYMAP_OFF:
1776 getIntl().keyMapOn(false);
1779 case LFUN_KEYMAP_PRIMARY:
1780 getIntl().keyMapPrim();
1783 case LFUN_KEYMAP_SECONDARY:
1784 getIntl().keyMapSec();
1787 case LFUN_KEYMAP_TOGGLE:
1788 getIntl().toggleKeyMap();
1791 case LFUN_DIALOG_SHOW_NEW_INSET: {
1792 string const name = cmd.getArg(0);
1793 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1794 if (decodeInsetParam(name, data, buffer_))
1795 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1797 lyxerr << "Inset type '" << name <<
1798 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1802 case LFUN_CITATION_INSERT: {
1803 if (argument.empty()) {
1804 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1807 // we can have one optional argument, delimited by '|'
1808 // citation-insert <key>|<text_before>
1809 // this should be enhanced to also support text_after
1810 // and citation style
1811 string arg = argument;
1813 if (contains(argument, "|")) {
1814 arg = token(argument, '|', 0);
1815 opt1 = token(argument, '|', 1);
1817 InsetCommandParams icp(CITE_CODE);
1818 icp["key"] = from_utf8(arg);
1820 icp["before"] = from_utf8(opt1);
1821 string icstr = InsetCommand::params2string("citation", icp);
1822 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1827 case LFUN_INSET_APPLY: {
1828 string const name = cmd.getArg(0);
1829 Inset * inset = editedInset(name);
1831 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1835 // put cursor in front of inset.
1836 if (!setCursorFromInset(inset)) {
1837 LASSERT(false, break);
1840 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1841 inset->dispatch(cur, fr);
1842 dr.update(Update::SinglePar | Update::FitCursor);
1851 buffer_.undo().endUndoGroup();
1852 dr.dispatched(dispatched);
1857 docstring const BufferView::requestSelection()
1859 Cursor & cur = d->cursor_;
1861 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1862 if (!cur.selection()) {
1863 d->xsel_cache_.set = false;
1867 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1868 if (!d->xsel_cache_.set ||
1869 cur.top() != d->xsel_cache_.cursor ||
1870 cur.anchor_.top() != d->xsel_cache_.anchor)
1872 d->xsel_cache_.cursor = cur.top();
1873 d->xsel_cache_.anchor = cur.anchor_.top();
1874 d->xsel_cache_.set = cur.selection();
1875 return cur.selectionAsString(false);
1881 void BufferView::clearSelection()
1883 d->cursor_.clearSelection();
1884 // Clear the selection buffer. Otherwise a subsequent
1885 // middle-mouse-button paste would use the selection buffer,
1886 // not the more current external selection.
1887 cap::clearSelection();
1888 d->xsel_cache_.set = false;
1889 // The buffer did not really change, but this causes the
1890 // redraw we need because we cleared the selection above.
1891 buffer_.changed(false);
1895 void BufferView::resize(int width, int height)
1897 // Update from work area
1901 // Clear the paragraph height cache.
1902 d->par_height_.clear();
1903 // Redo the metrics.
1908 Inset const * BufferView::getCoveringInset(Text const & text,
1911 TextMetrics & tm = d->text_metrics_[&text];
1912 Inset * inset = tm.checkInsetHit(x, y);
1916 if (!inset->descendable(*this))
1917 // No need to go further down if the inset is not
1921 size_t cell_number = inset->nargs();
1922 // Check all the inner cell.
1923 for (size_t i = 0; i != cell_number; ++i) {
1924 Text const * inner_text = inset->getText(i);
1927 Inset const * inset_deeper =
1928 getCoveringInset(*inner_text, x, y);
1930 return inset_deeper;
1938 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1940 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1942 // This is only called for mouse related events including
1943 // LFUN_FILE_OPEN generated by drag-and-drop.
1944 FuncRequest cmd = cmd0;
1946 Cursor old = cursor();
1948 cur.push(buffer_.inset());
1949 cur.setSelection(d->cursor_.selection());
1951 // Either the inset under the cursor or the
1952 // surrounding Text will handle this event.
1954 // make sure we stay within the screen...
1955 cmd.y = min(max(cmd.y, -1), height_);
1957 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1959 // Get inset under mouse, if there is one.
1960 Inset const * covering_inset =
1961 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1962 if (covering_inset == d->last_inset_)
1963 // Same inset, no need to do anything...
1966 bool need_redraw = false;
1967 // const_cast because of setMouseHover().
1968 Inset * inset = const_cast<Inset *>(covering_inset);
1970 // Remove the hint on the last hovered inset (if any).
1971 need_redraw |= d->last_inset_->setMouseHover(false);
1973 // Highlighted the newly hovered inset (if any).
1974 need_redraw |= inset->setMouseHover(true);
1975 d->last_inset_ = inset;
1979 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1980 << cmd.x << ", " << cmd.y << ")");
1982 d->update_strategy_ = DecorationUpdate;
1984 // This event (moving without mouse click) is not passed further.
1985 // This should be changed if it is further utilized.
1986 buffer_.changed(false);
1990 // Build temporary cursor.
1991 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1993 // Put anchor at the same position.
1996 cur.beginUndoGroup();
1998 // Try to dispatch to an non-editable inset near this position
1999 // via the temp cursor. If the inset wishes to change the real
2000 // cursor it has to do so explicitly by using
2001 // cur.bv().cursor() = cur; (or similar)
2003 inset->dispatch(cur, cmd);
2005 // Now dispatch to the temporary cursor. If the real cursor should
2006 // be modified, the inset's dispatch has to do so explicitly.
2007 if (!inset || !cur.result().dispatched())
2012 // Notify left insets
2015 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2017 cursor().fixIfBroken();
2020 // Do we have a selection?
2021 theSelection().haveSelection(cursor().selection());
2023 // If the command has been dispatched,
2024 if (cur.result().dispatched() || cur.result().update())
2025 processUpdateFlags(cur.result().update());
2029 void BufferView::lfunScroll(FuncRequest const & cmd)
2031 string const scroll_type = cmd.getArg(0);
2032 int const scroll_step =
2033 (scroll_type == "line") ? d->scrollbarParameters_.single_step
2034 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
2035 if (scroll_step == 0)
2037 string const scroll_quantity = cmd.getArg(1);
2038 if (scroll_quantity == "up")
2039 scrollUp(scroll_step);
2040 else if (scroll_quantity == "down")
2041 scrollDown(scroll_step);
2043 int const scroll_value = convert<int>(scroll_quantity);
2045 scroll(scroll_step * scroll_value);
2047 buffer_.changed(true);
2051 int BufferView::minVisiblePart()
2053 return 2 * defaultRowHeight();
2057 int BufferView::scroll(int y)
2060 return scrollDown(y);
2062 return scrollUp(-y);
2067 int BufferView::scrollDown(int offset)
2069 Text * text = &buffer_.text();
2070 TextMetrics & tm = d->text_metrics_[text];
2071 int const ymax = height_ + offset;
2073 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2074 int bottom_pos = last.second->position() + last.second->descent();
2075 if (lyxrc.scroll_below_document)
2076 bottom_pos += height_ - minVisiblePart();
2077 if (last.first + 1 == int(text->paragraphs().size())) {
2078 if (bottom_pos <= height_)
2080 offset = min(offset, bottom_pos - height_);
2083 if (bottom_pos > ymax)
2085 tm.newParMetricsDown();
2087 d->anchor_ypos_ -= offset;
2092 int BufferView::scrollUp(int offset)
2094 Text * text = &buffer_.text();
2095 TextMetrics & tm = d->text_metrics_[text];
2096 int ymin = - offset;
2098 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2099 int top_pos = first.second->position() - first.second->ascent();
2100 if (first.first == 0) {
2103 offset = min(offset, - top_pos);
2108 tm.newParMetricsUp();
2110 d->anchor_ypos_ += offset;
2115 void BufferView::setCursorFromRow(int row)
2120 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2124 buffer_.text().setCursor(d->cursor_, 0, 0);
2126 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
2131 bool BufferView::setCursorFromInset(Inset const * inset)
2133 // are we already there?
2134 if (cursor().nextInset() == inset)
2137 // Inset is not at cursor position. Find it in the document.
2140 while (cur && cur.nextInset() != inset)
2151 void BufferView::gotoLabel(docstring const & label)
2153 std::vector<Buffer const *> bufs = buffer().allRelatives();
2154 std::vector<Buffer const *>::iterator it = bufs.begin();
2155 for (; it != bufs.end(); ++it) {
2156 Buffer const * buf = *it;
2159 Toc & toc = buf->tocBackend().toc("label");
2160 TocIterator toc_it = toc.begin();
2161 TocIterator end = toc.end();
2162 for (; toc_it != end; ++toc_it) {
2163 if (label == toc_it->str()) {
2164 lyx::dispatch(toc_it->action());
2172 TextMetrics const & BufferView::textMetrics(Text const * t) const
2174 return const_cast<BufferView *>(this)->textMetrics(t);
2178 TextMetrics & BufferView::textMetrics(Text const * t)
2180 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2181 if (tmc_it == d->text_metrics_.end()) {
2182 tmc_it = d->text_metrics_.insert(
2183 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2185 return tmc_it->second;
2189 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2192 return textMetrics(t).parMetrics(pit);
2196 int BufferView::workHeight() const
2202 void BufferView::setCursor(DocIterator const & dit)
2205 size_t const n = dit.depth();
2206 for (size_t i = 0; i < n; ++i)
2207 dit[i].inset().edit(d->cursor_, true);
2209 d->cursor_.setCursor(dit);
2210 d->cursor_.setSelection(false);
2214 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2216 // Would be wrong to delete anything if we have a selection.
2217 if (cur.selection())
2220 bool need_anchor_change = false;
2221 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2222 need_anchor_change);
2224 if (need_anchor_change)
2232 buffer_.updateBuffer();
2233 buffer_.changed(true);
2238 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2240 LASSERT(&cur.bv() == this, /**/);
2243 // this event will clear selection so we save selection for
2244 // persistent selection
2245 cap::saveSelection(cursor());
2247 d->cursor_.macroModeClose();
2249 // Has the cursor just left the inset?
2250 bool leftinset = (&d->cursor_.inset() != &cur.inset());
2252 d->cursor_.fixIfBroken();
2254 // FIXME: shift-mouse selection doesn't work well across insets.
2255 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
2257 // do the dEPM magic if needed
2258 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2259 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2260 // the leftinset bool would not be necessary (badcursor instead).
2261 bool update = leftinset;
2262 if (!do_selection && d->cursor_.inTexted())
2263 update |= checkDepm(cur, d->cursor_);
2266 d->cursor_.resetAnchor();
2267 d->cursor_.setCursor(cur);
2268 d->cursor_.boundary(cur.boundary());
2270 d->cursor_.setSelection();
2272 d->cursor_.clearSelection();
2274 d->cursor_.finishUndo();
2275 d->cursor_.setCurrentFont();
2280 void BufferView::putSelectionAt(DocIterator const & cur,
2281 int length, bool backwards)
2283 d->cursor_.clearSelection();
2289 d->cursor_.pos() += length;
2290 d->cursor_.setSelection(d->cursor_, -length);
2292 d->cursor_.setSelection(d->cursor_, length);
2294 // Ensure a redraw happens in any case because the new selection could
2295 // possibly be on the same screen as the previous selection.
2296 processUpdateFlags(Update::Force | Update::FitCursor);
2300 Cursor & BufferView::cursor()
2306 Cursor const & BufferView::cursor() const
2312 pit_type BufferView::anchor_ref() const
2314 return d->anchor_pit_;
2318 bool BufferView::singleParUpdate()
2320 Text & buftext = buffer_.text();
2321 pit_type const bottom_pit = d->cursor_.bottom().pit();
2322 TextMetrics & tm = textMetrics(&buftext);
2323 int old_height = tm.parMetrics(bottom_pit).height();
2325 // make sure inline completion pointer is ok
2326 if (d->inlineCompletionPos_.fixIfBroken())
2327 d->inlineCompletionPos_ = DocIterator();
2329 // In Single Paragraph mode, rebreak only
2330 // the (main text, not inset!) paragraph containing the cursor.
2331 // (if this paragraph contains insets etc., rebreaking will
2332 // recursively descend)
2333 tm.redoParagraph(bottom_pit);
2334 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2335 if (pm.height() != old_height)
2336 // Paragraph height has changed so we cannot proceed to
2337 // the singlePar optimisation.
2340 d->update_strategy_ = SingleParUpdate;
2342 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2343 << " y2: " << pm.position() + pm.descent()
2344 << " pit: " << bottom_pit
2345 << " singlepar: 1");
2350 void BufferView::updateMetrics()
2352 if (height_ == 0 || width_ == 0)
2355 Text & buftext = buffer_.text();
2356 pit_type const npit = int(buftext.paragraphs().size());
2358 // Clear out the position cache in case of full screen redraw,
2359 d->coord_cache_.clear();
2361 // Clear out paragraph metrics to avoid having invalid metrics
2362 // in the cache from paragraphs not relayouted below
2363 // The complete text metrics will be redone.
2364 d->text_metrics_.clear();
2366 TextMetrics & tm = textMetrics(&buftext);
2368 // make sure inline completion pointer is ok
2369 if (d->inlineCompletionPos_.fixIfBroken())
2370 d->inlineCompletionPos_ = DocIterator();
2372 if (d->anchor_pit_ >= npit)
2373 // The anchor pit must have been deleted...
2374 d->anchor_pit_ = npit - 1;
2376 // Rebreak anchor paragraph.
2377 tm.redoParagraph(d->anchor_pit_);
2378 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2381 if (d->anchor_pit_ == 0) {
2382 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2384 // Complete buffer visible? Then it's easy.
2385 if (scrollRange == 0)
2386 d->anchor_ypos_ = anchor_pm.ascent();
2388 // FIXME: Some clever handling needed to show
2389 // the _first_ paragraph up to the top if the cursor is
2390 // in the first line.
2392 anchor_pm.setPosition(d->anchor_ypos_);
2394 LYXERR(Debug::PAINTING, "metrics: "
2395 << " anchor pit = " << d->anchor_pit_
2396 << " anchor ypos = " << d->anchor_ypos_);
2398 // Redo paragraphs above anchor if necessary.
2399 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2400 // We are now just above the anchor paragraph.
2401 pit_type pit1 = d->anchor_pit_ - 1;
2402 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2403 tm.redoParagraph(pit1);
2404 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2406 // Save the paragraph position in the cache.
2411 // Redo paragraphs below the anchor if necessary.
2412 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2413 // We are now just below the anchor paragraph.
2414 pit_type pit2 = d->anchor_pit_ + 1;
2415 for (; pit2 < npit && y2 <= height_; ++pit2) {
2416 tm.redoParagraph(pit2);
2417 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2419 // Save the paragraph position in the cache.
2424 LYXERR(Debug::PAINTING, "Metrics: "
2425 << " anchor pit = " << d->anchor_pit_
2426 << " anchor ypos = " << d->anchor_ypos_
2429 << " pit1 = " << pit1
2430 << " pit2 = " << pit2);
2432 d->update_strategy_ = FullScreenUpdate;
2434 if (lyxerr.debugging(Debug::WORKAREA)) {
2435 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2436 d->coord_cache_.dump();
2441 void BufferView::insertLyXFile(FileName const & fname)
2443 LASSERT(d->cursor_.inTexted(), /**/);
2445 // Get absolute path of file and add ".lyx"
2446 // to the filename if necessary
2447 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2449 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2450 // emit message signal.
2451 message(bformat(_("Inserting document %1$s..."), disp_fn));
2454 Buffer buf("", false);
2455 if (buf.loadLyXFile(filename)) {
2456 ErrorList & el = buffer_.errorList("Parse");
2457 // Copy the inserted document error list into the current buffer one.
2458 el = buf.errorList("Parse");
2459 buffer_.undo().recordUndo(d->cursor_);
2460 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2461 buf.params().documentClassPtr(), el);
2462 res = _("Document %1$s inserted.");
2464 res = _("Could not insert document %1$s");
2467 buffer_.changed(true);
2468 // emit message signal.
2469 message(bformat(res, disp_fn));
2470 buffer_.errors("Parse");
2474 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2480 // Addup contribution of nested insets, from inside to outside,
2481 // keeping the outer paragraph for a special handling below
2482 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2483 CursorSlice const & sl = dit[i];
2487 // get relative position inside sl.inset()
2488 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2490 // Make relative position inside of the edited inset relative to sl.inset()
2494 // In case of an RTL inset, the edited inset will be positioned to the left
2497 bool boundary_i = boundary && i + 1 == dit.depth();
2498 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2503 // remember width for the case that sl.inset() is positioned in an RTL inset
2504 if (i && dit[i - 1].text()) {
2505 // If this Inset is inside a Text Inset, retrieve the Dimension
2506 // from the containing text instead of using Inset::dimension() which
2507 // might not be implemented.
2508 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2509 // elimination of Inset::dim_ cache. This coordOffset() method needs
2510 // to be rewritten in light of the new design.
2511 Dimension const & dim = parMetrics(dit[i - 1].text(),
2512 dit[i - 1].pit()).insetDimension(&sl.inset());
2515 Dimension const dim = sl.inset().dimension(*this);
2519 //lyxerr << "Cursor::getPos, i: "
2520 // << i << " x: " << xx << " y: " << y << endl;
2523 // Add contribution of initial rows of outermost paragraph
2524 CursorSlice const & sl = dit[0];
2525 TextMetrics const & tm = textMetrics(sl.text());
2526 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2527 LASSERT(!pm.rows().empty(), /**/);
2528 y -= pm.rows()[0].ascent();
2530 // FIXME: document this mess
2532 if (sl.pos() > 0 && dit.depth() == 1) {
2534 if (pos && boundary)
2536 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2537 rend = pm.pos2row(pos);
2539 rend = pm.pos2row(sl.pos());
2541 size_t rend = pm.pos2row(sl.pos());
2543 for (size_t rit = 0; rit != rend; ++rit)
2544 y += pm.rows()[rit].height();
2545 y += pm.rows()[rend].ascent();
2547 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2549 // Make relative position from the nested inset now bufferview absolute.
2550 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2553 // In the RTL case place the nested inset at the left of the cursor in
2554 // the outer paragraph
2555 bool boundary_1 = boundary && 1 == dit.depth();
2556 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2564 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2566 if (!paragraphVisible(dit))
2567 return Point(-1, -1);
2569 CursorSlice const & bot = dit.bottom();
2570 TextMetrics const & tm = textMetrics(bot.text());
2572 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2573 p.y_ += tm.parMetrics(bot.pit()).position();
2578 bool BufferView::paragraphVisible(DocIterator const & dit) const
2580 CursorSlice const & bot = dit.bottom();
2581 TextMetrics const & tm = textMetrics(bot.text());
2583 return tm.contains(bot.pit());
2587 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2589 Cursor const & cur = cursor();
2590 Font const font = cur.getFont();
2591 frontend::FontMetrics const & fm = theFontMetrics(font);
2592 int const asc = fm.maxAscent();
2593 int const des = fm.maxDescent();
2595 p = getPos(cur, cur.boundary());
2600 bool BufferView::cursorInView(Point const & p, int h) const
2602 Cursor const & cur = cursor();
2603 // does the cursor touch the screen ?
2604 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2610 void BufferView::draw(frontend::Painter & pain)
2612 if (height_ == 0 || width_ == 0)
2614 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2616 Text & text = buffer_.text();
2617 TextMetrics const & tm = d->text_metrics_[&text];
2618 int const y = tm.first().second->position();
2619 PainterInfo pi(this, pain);
2621 switch (d->update_strategy_) {
2623 case NoScreenUpdate:
2624 // If no screen painting is actually needed, only some the different
2625 // coordinates of insets and paragraphs needs to be updated.
2626 pi.full_repaint = true;
2627 pi.pain.setDrawingEnabled(false);
2631 case SingleParUpdate:
2632 pi.full_repaint = false;
2633 // In general, only the current row of the outermost paragraph
2634 // will be redrawn. Particular cases where selection spans
2635 // multiple paragraph are correctly detected in TextMetrics.
2639 case DecorationUpdate:
2640 // FIXME: We should also distinguish DecorationUpdate to avoid text
2641 // drawing if possible. This is not possible to do easily right now
2642 // because of the single backing pixmap.
2644 case FullScreenUpdate:
2645 // The whole screen, including insets, will be refreshed.
2646 pi.full_repaint = true;
2648 // Clear background.
2649 pain.fillRectangle(0, 0, width_, height_,
2650 pi.backgroundColor(&buffer_.inset()));
2655 // and possibly grey out below
2656 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2657 int const y2 = lastpm.second->position() + lastpm.second->descent();
2660 Color color = buffer().isInternal()
2661 ? Color_background : Color_bottomarea;
2662 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2666 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2668 // The scrollbar needs an update.
2671 // Normalize anchor for next time
2672 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2673 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2674 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2675 ParagraphMetrics const & pm = tm.parMetrics(pit);
2676 if (pm.position() + pm.descent() > 0) {
2677 d->anchor_pit_ = pit;
2678 d->anchor_ypos_ = pm.position();
2682 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2683 << " anchor ypos = " << d->anchor_ypos_);
2687 void BufferView::message(docstring const & msg)
2690 d->gui_->message(msg);
2694 void BufferView::showDialog(string const & name)
2697 d->gui_->showDialog(name, string());
2701 void BufferView::showDialog(string const & name,
2702 string const & data, Inset * inset)
2705 d->gui_->showDialog(name, data, inset);
2709 void BufferView::updateDialog(string const & name, string const & data)
2712 d->gui_->updateDialog(name, data);
2716 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2722 // FIXME: Move this out of BufferView again
2723 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2725 if (!fname.isReadableFile()) {
2726 docstring const error = from_ascii(strerror(errno));
2727 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2728 docstring const text =
2729 bformat(_("Could not read the specified document\n"
2730 "%1$s\ndue to the error: %2$s"), file, error);
2731 Alert::error(_("Could not read file"), text);
2735 if (!fname.isReadableFile()) {
2736 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2737 docstring const text =
2738 bformat(_("%1$s\n is not readable."), file);
2739 Alert::error(_("Could not open file"), text);
2743 // FIXME UNICODE: We don't know the encoding of the file
2744 docstring file_content = fname.fileContents("UTF-8");
2745 if (file_content.empty()) {
2746 Alert::error(_("Reading not UTF-8 encoded file"),
2747 _("The file is not UTF-8 encoded.\n"
2748 "It will be read as local 8Bit-encoded.\n"
2749 "If this does not give the correct result\n"
2750 "then please change the encoding of the file\n"
2751 "to UTF-8 with a program other than LyX.\n"));
2752 file_content = fname.fileContents("local8bit");
2755 return normalize_c(file_content);
2759 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2761 docstring const tmpstr = contentsOfPlaintextFile(f);
2766 Cursor & cur = cursor();
2767 cap::replaceSelection(cur);
2768 buffer_.undo().recordUndo(cur);
2770 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2772 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2774 buffer_.changed(true);
2778 docstring const & BufferView::inlineCompletion() const
2780 return d->inlineCompletion_;
2784 size_t const & BufferView::inlineCompletionUniqueChars() const
2786 return d->inlineCompletionUniqueChars_;
2790 DocIterator const & BufferView::inlineCompletionPos() const
2792 return d->inlineCompletionPos_;
2796 bool samePar(DocIterator const & a, DocIterator const & b)
2798 if (a.empty() && b.empty())
2800 if (a.empty() || b.empty())
2802 if (a.depth() != b.depth())
2804 return &a.innerParagraph() == &b.innerParagraph();
2808 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2809 docstring const & completion, size_t uniqueChars)
2811 uniqueChars = min(completion.size(), uniqueChars);
2812 bool changed = d->inlineCompletion_ != completion
2813 || d->inlineCompletionUniqueChars_ != uniqueChars;
2814 bool singlePar = true;
2815 d->inlineCompletion_ = completion;
2816 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2818 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2821 DocIterator const & old = d->inlineCompletionPos_;
2823 //lyxerr << "inlineCompletionPos changed" << std::endl;
2824 // old or pos are in another paragraph?
2825 if ((!samePar(cur, pos) && !pos.empty())
2826 || (!samePar(cur, old) && !old.empty())) {
2828 //lyxerr << "different paragraph" << std::endl;
2830 d->inlineCompletionPos_ = pos;
2835 if (singlePar && !(cur.disp_.update() & Update::Force))
2836 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2838 cur.updateFlags(cur.disp_.update() | Update::Force);