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 // last_inset_ points to the last visited inset. This pointer may become
407 // invalid because of keyboard editing. Since all such operations
408 // causes screen update(), I reset last_inset_ to avoid such a problem.
411 // This is close to a hot-path.
412 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
413 << "[fitcursor = " << (flags & Update::FitCursor)
414 << ", forceupdate = " << (flags & Update::Force)
415 << ", singlepar = " << (flags & Update::SinglePar)
416 << "] buffer: " << &buffer_);
418 buffer_.updateMacros();
420 // Now do the first drawing step if needed. This consists on updating
421 // the CoordCache in updateMetrics().
422 // The second drawing step is done in WorkArea::redraw() if needed.
424 // Case when no explicit update is requested.
426 // no need to redraw anything.
427 d->update_strategy_ = NoScreenUpdate;
431 if (flags == Update::Decoration) {
432 d->update_strategy_ = DecorationUpdate;
433 buffer_.changed(false);
437 if (flags == Update::FitCursor
438 || flags == (Update::Decoration | Update::FitCursor)) {
439 // tell the frontend to update the screen if needed.
444 if (flags & Update::Decoration) {
445 d->update_strategy_ = DecorationUpdate;
446 buffer_.changed(false);
449 // no screen update is needed.
450 d->update_strategy_ = NoScreenUpdate;
454 bool const full_metrics = flags & Update::Force || !singleParUpdate();
457 // We have to update the full screen metrics.
460 if (!(flags & Update::FitCursor)) {
461 // Nothing to do anymore. Trigger a redraw and return
462 buffer_.changed(false);
466 // updateMetrics() does not update paragraph position
467 // This is done at draw() time. So we need a redraw!
468 buffer_.changed(false);
471 // The cursor is off screen so ensure it is visible.
476 updateHoveredInset();
480 void BufferView::updateScrollbar()
482 if (height_ == 0 && width_ == 0)
485 // We prefer fixed size line scrolling.
486 d->scrollbarParameters_.single_step = defaultRowHeight();
487 // We prefer full screen page scrolling.
488 d->scrollbarParameters_.page_step = height_;
490 Text & t = buffer_.text();
491 TextMetrics & tm = d->text_metrics_[&t];
493 LYXERR(Debug::GUI, " Updating scrollbar: height: "
494 << t.paragraphs().size()
495 << " curr par: " << d->cursor_.bottom().pit()
496 << " default height " << defaultRowHeight());
498 size_t const parsize = t.paragraphs().size();
499 if (d->par_height_.size() != parsize) {
500 d->par_height_.clear();
501 // FIXME: We assume a default paragraph height of 2 rows. This
502 // should probably be pondered with the screen width.
503 d->par_height_.resize(parsize, defaultRowHeight() * 2);
506 // Look at paragraph heights on-screen
507 pair<pit_type, ParagraphMetrics const *> first = tm.first();
508 pair<pit_type, ParagraphMetrics const *> last = tm.last();
509 for (pit_type pit = first.first; pit <= last.first; ++pit) {
510 d->par_height_[pit] = tm.parMetrics(pit).height();
511 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
512 << d->par_height_[pit]);
515 int top_pos = first.second->position() - first.second->ascent();
516 int bottom_pos = last.second->position() + last.second->descent();
517 bool first_visible = first.first == 0 && top_pos >= 0;
518 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
519 if (first_visible && last_visible) {
520 d->scrollbarParameters_.min = 0;
521 d->scrollbarParameters_.max = 0;
525 d->scrollbarParameters_.min = top_pos;
526 for (size_t i = 0; i != size_t(first.first); ++i)
527 d->scrollbarParameters_.min -= d->par_height_[i];
528 d->scrollbarParameters_.max = bottom_pos;
529 for (size_t i = last.first + 1; i != parsize; ++i)
530 d->scrollbarParameters_.max += d->par_height_[i];
532 d->scrollbarParameters_.position = 0;
533 // The reference is the top position so we remove one page.
534 if (lyxrc.scroll_below_document)
535 d->scrollbarParameters_.max -= minVisiblePart();
537 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
541 ScrollbarParameters const & BufferView::scrollbarParameters() const
543 return d->scrollbarParameters_;
547 docstring BufferView::toolTip(int x, int y) const
549 // Get inset under mouse, if there is one.
550 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
552 // No inset, no tooltip...
554 return covering_inset->toolTip(*this, x, y);
558 docstring BufferView::contextMenu(int x, int y) const
560 //If there is a selection, return the containing inset menu
561 if (d->cursor_.selection())
562 return d->cursor_.inset().contextMenu(*this, x, y);
564 // Get inset under mouse, if there is one.
565 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
567 return covering_inset->contextMenu(*this, x, y);
569 return buffer_.inset().contextMenu(*this, x, y);
573 void BufferView::scrollDocView(int value)
575 int const offset = value - d->scrollbarParameters_.position;
577 // No scrolling at all? No need to redraw anything
581 // If the offset is less than 2 screen height, prefer to scroll instead.
582 if (abs(offset) <= 2 * height_) {
583 d->anchor_ypos_ -= offset;
584 buffer_.changed(true);
585 updateHoveredInset();
589 // cut off at the top
590 if (value <= d->scrollbarParameters_.min) {
591 DocIterator dit = doc_iterator_begin(&buffer_);
593 LYXERR(Debug::SCROLLING, "scroll to top");
597 // cut off at the bottom
598 if (value >= d->scrollbarParameters_.max) {
599 DocIterator dit = doc_iterator_end(&buffer_);
602 LYXERR(Debug::SCROLLING, "scroll to bottom");
606 // find paragraph at target position
607 int par_pos = d->scrollbarParameters_.min;
609 for (; i != int(d->par_height_.size()); ++i) {
610 par_pos += d->par_height_[i];
611 if (par_pos >= value)
615 if (par_pos < value) {
616 // It seems we didn't find the correct pit so stay on the safe side and
618 LYXERR0("scrolling position not found!");
619 scrollDocView(d->scrollbarParameters_.max);
623 DocIterator dit = doc_iterator_begin(&buffer_);
625 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
630 // FIXME: this method is not working well.
631 void BufferView::setCursorFromScrollbar()
633 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
635 int const height = 2 * defaultRowHeight();
636 int const first = height;
637 int const last = height_ - height;
639 Cursor const & oldcur = d->cursor_;
641 switch (cursorStatus(oldcur)) {
649 int const y = getPos(oldcur, oldcur.boundary()).y_;
650 newy = min(last, max(y, first));
654 // We reset the cursor because cursorStatus() does not
655 // work when the cursor is within mathed.
658 tm.setCursorFromCoordinates(cur, 0, newy);
660 // update the bufferview cursor and notify insets
661 // FIXME: Care about the d->cursor_ flags to redraw if needed
662 Cursor old = d->cursor_;
664 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
666 d->cursor_.fixIfBroken();
670 Change const BufferView::getCurrentChange() const
672 if (!d->cursor_.selection())
673 return Change(Change::UNCHANGED);
675 DocIterator dit = d->cursor_.selectionBegin();
676 return dit.paragraph().lookupChange(dit.pos());
680 // this could be used elsewhere as well?
681 // FIXME: This does not work within mathed!
682 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
684 Point const p = getPos(dit, dit.boundary());
687 if (p.y_ > workHeight())
693 void BufferView::bookmarkEditPosition()
695 // Don't eat cpu time for each keystroke
696 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
699 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
703 void BufferView::saveBookmark(unsigned int idx)
705 // tentatively save bookmark, id and pos will be used to
706 // acturately locate a bookmark in a 'live' lyx session.
707 // pit and pos will be updated with bottom level pit/pos
709 if (!buffer_.isInternal()) {
710 theSession().bookmarks().save(
712 d->cursor_.bottom().pit(),
713 d->cursor_.bottom().pos(),
714 d->cursor_.paragraph().id(),
719 // emit message signal.
720 message(_("Save bookmark"));
725 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
726 int top_id, pos_type top_pos)
728 bool success = false;
731 d->cursor_.clearSelection();
733 // if a valid par_id is given, try it first
734 // This is the case for a 'live' bookmark when unique paragraph ID
735 // is used to track bookmarks.
737 dit = buffer_.getParFromID(top_id);
739 dit.pos() = min(dit.paragraph().size(), top_pos);
740 // Some slices of the iterator may not be
741 // reachable (e.g. closed collapsable inset)
742 // so the dociterator may need to be
743 // shortened. Otherwise, setCursor may crash
744 // lyx when the cursor can not be set to these
746 size_t const n = dit.depth();
747 for (size_t i = 0; i < n; ++i)
748 if (!dit[i].inset().editable()) {
756 // if top_id == 0, or searching through top_id failed
757 // This is the case for a 'restored' bookmark when only bottom
758 // (document level) pit was saved. Because of this, bookmark
759 // restoration is inaccurate. If a bookmark was within an inset,
760 // it will be restored to the left of the outmost inset that contains
762 if (bottom_pit < int(buffer_.paragraphs().size())) {
763 dit = doc_iterator_begin(&buffer_);
765 dit.pit() = bottom_pit;
766 dit.pos() = min(bottom_pos, dit.paragraph().size());
771 // Note: only bottom (document) level pit is set.
773 // set the current font.
774 d->cursor_.setCurrentFont();
775 // To center the screen on this new position we need the
776 // paragraph position which is computed at draw() time.
777 // So we need a redraw!
778 buffer_.changed(false);
787 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
789 if (lyxrc.rtl_support) {
790 if (d->cursor_.real_current_font.isRightToLeft()) {
791 if (d->intl_.keymap == Intl::PRIMARY)
792 d->intl_.keyMapSec();
794 if (d->intl_.keymap == Intl::SECONDARY)
795 d->intl_.keyMapPrim();
799 d->intl_.getTransManager().translateAndInsert(c, t, cur);
803 int BufferView::workWidth() const
809 void BufferView::recenter()
811 showCursor(d->cursor_, true);
815 void BufferView::showCursor()
817 showCursor(d->cursor_, false);
821 void BufferView::showCursor(DocIterator const & dit, bool recenter)
823 if (scrollToCursor(dit, recenter)) {
824 buffer_.changed(true);
825 updateHoveredInset();
830 void BufferView::scrollToCursor()
832 if (scrollToCursor(d->cursor_, false)) {
833 buffer_.changed(true);
834 updateHoveredInset();
839 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
841 // We are not properly started yet, delay until resizing is
846 LYXERR(Debug::SCROLLING, "recentering!");
848 CursorSlice const & bot = dit.bottom();
849 TextMetrics & tm = d->text_metrics_[bot.text()];
851 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
852 int bot_pit = bot.pit();
853 if (bot_pit > max_pit) {
854 // FIXME: Why does this happen?
855 LYXERR0("bottom pit is greater that max pit: "
856 << bot_pit << " > " << max_pit);
860 if (bot_pit == tm.first().first - 1)
861 tm.newParMetricsUp();
862 else if (bot_pit == tm.last().first + 1)
863 tm.newParMetricsDown();
865 if (tm.contains(bot_pit)) {
866 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
867 LASSERT(!pm.rows().empty(), /**/);
868 // FIXME: smooth scrolling doesn't work in mathed.
869 CursorSlice const & cs = dit.innerTextSlice();
870 int offset = coordOffset(dit, dit.boundary()).y_;
871 int ypos = pm.position() + offset;
872 Dimension const & row_dim =
873 pm.getRow(cs.pos(), dit.boundary()).dimension();
876 scrolled = scroll(ypos - height_/2);
877 else if (ypos - row_dim.ascent() < 0)
878 scrolled = scrollUp(- ypos + row_dim.ascent());
879 else if (ypos + row_dim.descent() > height_)
880 scrolled = scrollDown(ypos - height_ + defaultRowHeight() );
882 // else, nothing to do, the cursor is already visible so we just return.
883 return scrolled != 0;
886 // fix inline completion position
887 if (d->inlineCompletionPos_.fixIfBroken())
888 d->inlineCompletionPos_ = DocIterator();
890 tm.redoParagraph(bot_pit);
891 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
892 int offset = coordOffset(dit, dit.boundary()).y_;
894 d->anchor_pit_ = bot_pit;
895 CursorSlice const & cs = dit.innerTextSlice();
896 Dimension const & row_dim =
897 pm.getRow(cs.pos(), dit.boundary()).dimension();
900 d->anchor_ypos_ = height_/2;
901 else if (d->anchor_pit_ == 0)
902 d->anchor_ypos_ = offset + pm.ascent();
903 else if (d->anchor_pit_ == max_pit)
904 d->anchor_ypos_ = height_ - offset - row_dim.descent();
905 else if (offset > height_)
906 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
908 d->anchor_ypos_ = defaultRowHeight() * 2;
914 void BufferView::updateDocumentClass(DocumentClass const * const olddc)
916 message(_("Converting document to new document class..."));
918 StableDocIterator backcur(d->cursor_);
919 ErrorList & el = buffer_.errorList("Class Switch");
920 cap::switchBetweenClasses(
921 olddc, buffer_.params().documentClassPtr(),
922 static_cast<InsetText &>(buffer_.inset()), el);
924 setCursor(backcur.asDocIterator(&buffer_));
926 buffer_.errors("Class Switch");
927 buffer_.updateBuffer();
930 /** Return the change status at cursor position, taking in account the
931 * status at each level of the document iterator (a table in a deleted
932 * footnote is deleted).
933 * When \param outer is true, the top slice is not looked at.
935 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
937 size_t const depth = dit.depth() - (outer ? 1 : 0);
939 for (size_t i = 0 ; i < depth ; ++i) {
940 CursorSlice const & slice = dit[i];
941 if (!slice.inset().inMathed()
942 && slice.pos() < slice.paragraph().size()) {
943 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
944 if (ch != Change::UNCHANGED)
948 return Change::UNCHANGED;
952 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
954 FuncCode const act = cmd.action();
956 // Can we use a readonly buffer?
957 if (buffer_.isReadonly()
958 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
959 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
960 flag.message(from_utf8(N_("Document is read-only")));
961 flag.setEnabled(false);
965 // Are we in a DELETED change-tracking region?
966 if (lookupChangeType(d->cursor_, true) == Change::DELETED
967 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
968 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
969 flag.message(from_utf8(N_("This portion of the document is deleted.")));
970 flag.setEnabled(false);
974 Cursor & cur = d->cursor_;
976 if (cur.getStatus(cmd, flag))
981 // FIXME: This is a bit problematic because we don't check if this is
982 // a document BufferView or not for these LFUNs. We probably have to
983 // dispatch both to currentBufferView() and, if that fails,
984 // to documentBufferView(); same as we do know for current Buffer and
985 // document Buffer. Ideally those LFUN should go to Buffer as they*
986 // operate on the full Buffer and the cursor is only needed either for
987 // an Undo record or to restore a cursor position. But we don't know
988 // how to do that inside Buffer of course.
989 case LFUN_BUFFER_PARAMS_APPLY:
990 case LFUN_LAYOUT_MODULES_CLEAR:
991 case LFUN_LAYOUT_MODULE_ADD:
992 case LFUN_LAYOUT_RELOAD:
993 case LFUN_TEXTCLASS_APPLY:
994 case LFUN_TEXTCLASS_LOAD:
995 flag.setEnabled(!buffer_.isReadonly());
999 flag.setEnabled(buffer_.undo().hasUndoStack());
1002 flag.setEnabled(buffer_.undo().hasRedoStack());
1004 case LFUN_FILE_INSERT:
1005 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1006 case LFUN_FILE_INSERT_PLAINTEXT:
1007 case LFUN_BOOKMARK_SAVE:
1008 // FIXME: Actually, these LFUNS should be moved to Text
1009 flag.setEnabled(cur.inTexted());
1012 case LFUN_FONT_STATE:
1013 case LFUN_LABEL_INSERT:
1014 case LFUN_INFO_INSERT:
1015 case LFUN_INSET_EDIT:
1016 case LFUN_PARAGRAPH_GOTO:
1017 case LFUN_NOTE_NEXT:
1018 case LFUN_REFERENCE_NEXT:
1019 case LFUN_WORD_FIND:
1020 case LFUN_WORD_FIND_FORWARD:
1021 case LFUN_WORD_FIND_BACKWARD:
1022 case LFUN_WORD_FINDADV:
1023 case LFUN_WORD_REPLACE:
1026 case LFUN_MARK_TOGGLE:
1027 case LFUN_SCREEN_RECENTER:
1028 case LFUN_SCREEN_SHOW_CURSOR:
1029 case LFUN_BIBTEX_DATABASE_ADD:
1030 case LFUN_BIBTEX_DATABASE_DEL:
1031 case LFUN_STATISTICS:
1032 case LFUN_BRANCH_ADD_INSERT:
1033 case LFUN_KEYMAP_OFF:
1034 case LFUN_KEYMAP_PRIMARY:
1035 case LFUN_KEYMAP_SECONDARY:
1036 case LFUN_KEYMAP_TOGGLE:
1037 flag.setEnabled(true);
1040 case LFUN_LABEL_COPY_AS_REF: {
1041 // if there is an inset at cursor, see whether it
1043 Inset * inset = cur.nextInset();
1044 if (!inset || !inset->getStatus(cur, cmd, flag))
1045 flag.setEnabled(false);
1049 case LFUN_LABEL_GOTO: {
1050 flag.setEnabled(!cmd.argument().empty()
1051 || getInsetByCode<InsetRef>(cur, REF_CODE));
1055 case LFUN_CHANGES_TRACK:
1056 flag.setEnabled(true);
1057 flag.setOnOff(buffer_.params().trackChanges);
1060 case LFUN_CHANGES_OUTPUT:
1061 flag.setEnabled(true);
1062 flag.setOnOff(buffer_.params().outputChanges);
1065 case LFUN_CHANGES_MERGE:
1066 case LFUN_CHANGE_NEXT:
1067 case LFUN_CHANGE_PREVIOUS:
1068 case LFUN_ALL_CHANGES_ACCEPT:
1069 case LFUN_ALL_CHANGES_REJECT:
1070 // TODO: context-sensitive enabling of LFUNs
1071 // In principle, these command should only be enabled if there
1072 // is a change in the document. However, without proper
1073 // optimizations, this will inevitably result in poor performance.
1074 flag.setEnabled(true);
1077 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1078 flag.setOnOff(buffer_.params().compressed);
1082 case LFUN_SCREEN_UP:
1083 case LFUN_SCREEN_DOWN:
1085 case LFUN_SCREEN_UP_SELECT:
1086 case LFUN_SCREEN_DOWN_SELECT:
1087 case LFUN_INSET_FORALL:
1088 flag.setEnabled(true);
1091 case LFUN_LAYOUT_TABULAR:
1092 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1096 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1099 case LFUN_LAYOUT_PARAGRAPH:
1100 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1103 case LFUN_DIALOG_SHOW_NEW_INSET:
1104 // FIXME: this is wrong, but I do not understand the
1106 if (cur.inset().lyxCode() == CAPTION_CODE)
1107 return cur.inset().getStatus(cur, cmd, flag);
1108 // FIXME we should consider passthru paragraphs too.
1109 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1112 case LFUN_CITATION_INSERT: {
1113 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1114 // FIXME: This could turn in a recursive hell.
1115 // Shouldn't we use Buffer::getStatus() instead?
1116 flag.setEnabled(lyx::getStatus(fr).enabled());
1119 case LFUN_INSET_APPLY: {
1120 string const name = cmd.getArg(0);
1121 Inset * inset = editedInset(name);
1123 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1124 if (!inset->getStatus(cur, fr, flag)) {
1125 // Every inset is supposed to handle this
1126 LASSERT(false, break);
1129 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1130 flag = lyx::getStatus(fr);
1136 flag.setEnabled(false);
1144 Inset * BufferView::editedInset(string const & name) const
1146 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1147 return it == d->edited_insets_.end() ? 0 : it->second;
1151 void BufferView::editInset(string const & name, Inset * inset)
1153 d->edited_insets_[name] = inset;
1157 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1159 //lyxerr << [ cmd = " << cmd << "]" << endl;
1161 // Make sure that the cached BufferView is correct.
1162 LYXERR(Debug::ACTION, " action[" << cmd.action() << ']'
1163 << " arg[" << to_utf8(cmd.argument()) << ']'
1164 << " x[" << cmd.x() << ']'
1165 << " y[" << cmd.y() << ']'
1166 << " button[" << cmd.button() << ']');
1168 string const argument = to_utf8(cmd.argument());
1169 Cursor & cur = d->cursor_;
1171 // Don't dispatch function that does not apply to internal buffers.
1172 if (buffer_.isInternal()
1173 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1176 // We'll set this back to false if need be.
1177 bool dispatched = true;
1178 buffer_.undo().beginUndoGroup();
1180 FuncCode const act = cmd.action();
1183 case LFUN_BUFFER_PARAMS_APPLY: {
1184 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1185 cur.recordUndoFullDocument();
1186 istringstream ss(to_utf8(cmd.argument()));
1189 int const unknown_tokens = buffer_.readHeader(lex);
1190 if (unknown_tokens != 0) {
1191 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1192 << unknown_tokens << " unknown token"
1193 << (unknown_tokens == 1 ? "" : "s"));
1195 updateDocumentClass(oldClass);
1197 // We are most certainly here because of a change in the document
1198 // It is then better to make sure that all dialogs are in sync with
1199 // current document settings.
1200 dr.update(Update::Force | Update::FitCursor);
1204 case LFUN_LAYOUT_MODULES_CLEAR: {
1205 DocumentClass const * const oldClass =
1206 buffer_.params().documentClassPtr();
1207 cur.recordUndoFullDocument();
1208 buffer_.params().clearLayoutModules();
1209 buffer_.params().makeDocumentClass();
1210 updateDocumentClass(oldClass);
1211 dr.update(Update::Force | Update::FitCursor);
1215 case LFUN_LAYOUT_MODULE_ADD: {
1216 BufferParams const & params = buffer_.params();
1217 if (!params.moduleCanBeAdded(argument)) {
1218 LYXERR0("Module `" << argument <<
1219 "' cannot be added due to failed requirements or "
1220 "conflicts with installed modules.");
1223 DocumentClass const * const oldClass = params.documentClassPtr();
1224 cur.recordUndoFullDocument();
1225 buffer_.params().addLayoutModule(argument);
1226 buffer_.params().makeDocumentClass();
1227 updateDocumentClass(oldClass);
1228 dr.update(Update::Force | Update::FitCursor);
1232 case LFUN_TEXTCLASS_APPLY: {
1233 if (!LayoutFileList::get().load(argument, buffer_.temppath()) &&
1234 !LayoutFileList::get().load(argument, buffer_.filePath()))
1237 LayoutFile const * old_layout = buffer_.params().baseClass();
1238 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1240 if (old_layout == new_layout)
1244 //Save the old, possibly modular, layout for use in conversion.
1245 DocumentClass const * const oldDocClass =
1246 buffer_.params().documentClassPtr();
1247 cur.recordUndoFullDocument();
1248 buffer_.params().setBaseClass(argument);
1249 buffer_.params().makeDocumentClass();
1250 updateDocumentClass(oldDocClass);
1251 dr.update(Update::Force | Update::FitCursor);
1255 case LFUN_TEXTCLASS_LOAD:
1256 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1257 LayoutFileList::get().load(argument, buffer_.filePath());
1260 case LFUN_LAYOUT_RELOAD: {
1261 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1262 LayoutFileIndex bc = buffer_.params().baseClassID();
1263 LayoutFileList::get().reset(bc);
1264 buffer_.params().setBaseClass(bc);
1265 buffer_.params().makeDocumentClass();
1266 updateDocumentClass(oldClass);
1267 dr.update(Update::Force | Update::FitCursor);
1272 dr.setMessage(_("Undo"));
1273 cur.clearSelection();
1274 if (!cur.textUndo())
1275 dr.setMessage(_("No further undo information"));
1277 dr.update(Update::Force | Update::FitCursor);
1281 dr.setMessage(_("Redo"));
1282 cur.clearSelection();
1283 if (!cur.textRedo())
1284 dr.setMessage(_("No further redo information"));
1286 dr.update(Update::Force | Update::FitCursor);
1289 case LFUN_FONT_STATE:
1290 dr.setMessage(cur.currentState());
1293 case LFUN_BOOKMARK_SAVE:
1294 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1297 case LFUN_LABEL_GOTO: {
1298 docstring label = cmd.argument();
1299 if (label.empty()) {
1301 getInsetByCode<InsetRef>(cur, REF_CODE);
1303 label = inset->getParam("reference");
1304 // persistent=false: use temp_bookmark
1313 case LFUN_INSET_EDIT: {
1314 FuncRequest fr(cmd);
1315 // if there is an inset at cursor, see whether it
1317 Inset * inset = cur.nextInset();
1319 inset->dispatch(cur, fr);
1320 // if it did not work, try the underlying inset.
1321 if (!inset || !cur.result().dispatched())
1324 // FIXME I'm adding the last break to solve a crash,
1325 // but that is obviously not right.
1326 if (!cur.result().dispatched())
1327 // It did not work too; no action needed.
1332 case LFUN_PARAGRAPH_GOTO: {
1333 int const id = convert<int>(cmd.getArg(0));
1334 int const pos = convert<int>(cmd.getArg(1));
1336 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1337 b = theBufferList().next(b)) {
1339 DocIterator dit = b->getParFromID(id);
1341 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1345 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1346 << " found in buffer `"
1347 << b->absFileName() << "'.");
1349 if (b == &buffer_) {
1353 dr.update(Update::Force | Update::FitCursor);
1355 // Switch to other buffer view and resend cmd
1356 lyx::dispatch(FuncRequest(
1357 LFUN_BUFFER_SWITCH, b->absFileName()));
1365 case LFUN_NOTE_NEXT:
1366 gotoInset(this, NOTE_CODE, false);
1369 case LFUN_REFERENCE_NEXT: {
1370 vector<InsetCode> tmp;
1371 tmp.push_back(LABEL_CODE);
1372 tmp.push_back(REF_CODE);
1373 gotoInset(this, tmp, true);
1377 case LFUN_CHANGES_TRACK:
1378 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1381 case LFUN_CHANGES_OUTPUT:
1382 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1383 if (buffer_.params().outputChanges) {
1384 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1385 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1386 LaTeXFeatures::isAvailable("xcolor");
1388 if (!dvipost && !xcolorulem) {
1389 Alert::warning(_("Changes not shown in LaTeX output"),
1390 _("Changes will not be highlighted in LaTeX output, "
1391 "because neither dvipost nor xcolor/ulem are installed.\n"
1392 "Please install these packages or redefine "
1393 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1394 } else if (!xcolorulem) {
1395 Alert::warning(_("Changes not shown in LaTeX output"),
1396 _("Changes will not be highlighted in LaTeX output "
1397 "when using pdflatex, because xcolor and ulem are not installed.\n"
1398 "Please install both packages or redefine "
1399 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1404 case LFUN_CHANGE_NEXT:
1405 findNextChange(this);
1406 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1407 dr.update(Update::Force | Update::FitCursor);
1410 case LFUN_CHANGE_PREVIOUS:
1411 findPreviousChange(this);
1412 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1413 dr.update(Update::Force | Update::FitCursor);
1416 case LFUN_CHANGES_MERGE:
1417 if (findNextChange(this) || findPreviousChange(this)) {
1418 dr.update(Update::Force | Update::FitCursor);
1419 showDialog("changes");
1423 case LFUN_ALL_CHANGES_ACCEPT:
1424 // select complete document
1426 cur.selHandle(true);
1427 buffer_.text().cursorBottom(cur);
1428 // accept everything in a single step to support atomic undo
1429 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1430 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1431 dr.update(Update::Force | Update::FitCursor);
1434 case LFUN_ALL_CHANGES_REJECT:
1435 // select complete document
1437 cur.selHandle(true);
1438 buffer_.text().cursorBottom(cur);
1439 // reject everything in a single step to support atomic undo
1440 // Note: reject does not work recursively; the user may have to repeat the operation
1441 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1442 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1443 dr.update(Update::Force | Update::FitCursor);
1446 case LFUN_WORD_FIND_FORWARD:
1447 case LFUN_WORD_FIND_BACKWARD: {
1448 static docstring last_search;
1449 docstring searched_string;
1451 if (!cmd.argument().empty()) {
1452 last_search = cmd.argument();
1453 searched_string = cmd.argument();
1455 searched_string = last_search;
1458 if (searched_string.empty())
1461 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1462 docstring const data =
1463 find2string(searched_string, true, false, fw);
1464 find(this, FuncRequest(LFUN_WORD_FIND, data));
1468 case LFUN_WORD_FIND: {
1469 FuncRequest req = cmd;
1470 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1471 req = d->search_request_cache_;
1472 if (req.argument().empty()) {
1473 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1476 if (find(this, req))
1479 message(_("String not found!"));
1480 d->search_request_cache_ = req;
1484 case LFUN_WORD_REPLACE: {
1485 bool has_deleted = false;
1486 if (cur.selection()) {
1487 DocIterator beg = cur.selectionBegin();
1488 DocIterator end = cur.selectionEnd();
1489 if (beg.pit() == end.pit()) {
1490 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1492 && cur.paragraph().isDeleted(p))
1497 replace(this, cmd, has_deleted);
1501 case LFUN_WORD_FINDADV: {
1502 FindAndReplaceOptions opt;
1503 istringstream iss(to_utf8(cmd.argument()));
1505 if (findAdv(this, opt))
1513 cur.clearSelection();
1514 dr.setMessage(from_utf8(N_("Mark off")));
1518 cur.clearSelection();
1520 dr.setMessage(from_utf8(N_("Mark on")));
1523 case LFUN_MARK_TOGGLE:
1524 cur.setSelection(false);
1527 dr.setMessage(from_utf8(N_("Mark removed")));
1530 dr.setMessage(from_utf8(N_("Mark set")));
1535 case LFUN_SCREEN_SHOW_CURSOR:
1539 case LFUN_SCREEN_RECENTER:
1543 case LFUN_BIBTEX_DATABASE_ADD: {
1544 Cursor tmpcur = cur;
1545 findInset(tmpcur, BIBTEX_CODE, false);
1546 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1549 if (inset->addDatabase(cmd.argument()))
1550 buffer_.updateBibfilesCache();
1555 case LFUN_BIBTEX_DATABASE_DEL: {
1556 Cursor tmpcur = cur;
1557 findInset(tmpcur, BIBTEX_CODE, false);
1558 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1561 if (inset->delDatabase(cmd.argument()))
1562 buffer_.updateBibfilesCache();
1567 case LFUN_STATISTICS: {
1568 DocIterator from, to;
1569 if (cur.selection()) {
1570 from = cur.selectionBegin();
1571 to = cur.selectionEnd();
1573 from = doc_iterator_begin(&buffer_);
1574 to = doc_iterator_end(&buffer_);
1576 int const words = countWords(from, to);
1577 int const chars = countChars(from, to, false);
1578 int const chars_blanks = countChars(from, to, true);
1580 if (cur.selection())
1581 message = _("Statistics for the selection:");
1583 message = _("Statistics for the document:");
1586 message += bformat(_("%1$d words"), words);
1588 message += _("One word");
1590 if (chars_blanks != 1)
1591 message += bformat(_("%1$d characters (including blanks)"),
1594 message += _("One character (including blanks)");
1597 message += bformat(_("%1$d characters (excluding blanks)"),
1600 message += _("One character (excluding blanks)");
1602 Alert::information(_("Statistics"), message);
1606 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1607 // turn compression on/off
1608 buffer_.params().compressed = !buffer_.params().compressed;
1611 case LFUN_LABEL_COPY_AS_REF: {
1612 // if there is an inset at cursor, try to copy it
1613 Inset * inset = &cur.inset();
1614 if (!inset || !inset->asInsetMath())
1615 inset = cur.nextInset();
1617 FuncRequest tmpcmd = cmd;
1618 inset->dispatch(cur, tmpcmd);
1620 if (!cur.result().dispatched())
1621 // It did not work too; no action needed.
1623 cur.clearSelection();
1624 dr.update(Update::SinglePar | Update::FitCursor);
1628 case LFUN_SCREEN_UP:
1629 case LFUN_SCREEN_DOWN: {
1630 Point p = getPos(cur, cur.boundary());
1631 // This code has been commented out to enable to scroll down a
1632 // document, even if there are large insets in it (see bug #5465).
1633 /*if (p.y_ < 0 || p.y_ > height_) {
1634 // The cursor is off-screen so recenter before proceeding.
1636 p = getPos(cur, cur.boundary());
1638 int const scrolled = scroll(act == LFUN_SCREEN_UP
1639 ? -height_ : height_);
1640 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1642 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1643 p = Point(width_, height_);
1645 bool const in_texted = cur.inTexted();
1647 buffer_.changed(true);
1648 updateHoveredInset();
1650 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1651 true, act == LFUN_SCREEN_UP);
1652 //FIXME: what to do with cur.x_target()?
1653 bool update = in_texted && cur.bv().checkDepm(cur, old);
1656 dr.update(Update::Force | Update::FitCursor);
1664 case LFUN_SCREEN_UP_SELECT: {
1665 cur.selHandle(true);
1666 if (isTopScreen()) {
1667 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1671 int y = getPos(cur, cur.boundary()).y_;
1672 int const ymin = y - height_ + defaultRowHeight();
1673 while (y > ymin && cur.up())
1674 y = getPos(cur, cur.boundary()).y_;
1677 dr.update(Update::SinglePar | Update::FitCursor);
1681 case LFUN_SCREEN_DOWN_SELECT: {
1682 cur.selHandle(true);
1683 if (isBottomScreen()) {
1684 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1688 int y = getPos(cur, cur.boundary()).y_;
1689 int const ymax = y + height_ - defaultRowHeight();
1690 while (y < ymax && cur.down())
1691 y = getPos(cur, cur.boundary()).y_;
1694 dr.update(Update::SinglePar | Update::FitCursor);
1699 // This would be in Buffer class if only Cursor did not
1700 // require a bufferview
1701 case LFUN_INSET_FORALL: {
1702 docstring const name = from_utf8(cmd.getArg(0));
1703 string const commandstr = cmd.getLongArg(1);
1704 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1706 // an arbitrary number to limit number of iterations
1707 const int max_iter = 10000;
1709 Cursor & cur = d->cursor_;
1710 Cursor const savecur = cur;
1712 if (!cur.nextInset())
1714 cur.beginUndoGroup();
1715 while(cur && iterations < max_iter) {
1716 Inset * ins = cur.nextInset();
1719 docstring insname = ins->name();
1720 while (!insname.empty()) {
1721 if (insname == name || name == from_utf8("*")) {
1723 lyx::dispatch(fr, dr);
1727 size_t const i = insname.rfind(':');
1728 if (i == string::npos)
1730 insname = insname.substr(0, i);
1737 dr.update(Update::Force);
1739 if (iterations >= max_iter) {
1741 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1743 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1748 case LFUN_BRANCH_ADD_INSERT: {
1749 docstring branch_name = from_utf8(cmd.getArg(0));
1750 if (branch_name.empty())
1751 if (!Alert::askForText(branch_name, _("Branch name")) ||
1752 branch_name.empty())
1755 DispatchResult drtmp;
1756 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1757 if (drtmp.error()) {
1758 Alert::warning(_("Branch already exists"), drtmp.message());
1761 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1765 case LFUN_KEYMAP_OFF:
1766 getIntl().keyMapOn(false);
1769 case LFUN_KEYMAP_PRIMARY:
1770 getIntl().keyMapPrim();
1773 case LFUN_KEYMAP_SECONDARY:
1774 getIntl().keyMapSec();
1777 case LFUN_KEYMAP_TOGGLE:
1778 getIntl().toggleKeyMap();
1781 case LFUN_DIALOG_SHOW_NEW_INSET: {
1782 string const name = cmd.getArg(0);
1783 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1784 if (decodeInsetParam(name, data, buffer_))
1785 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1787 lyxerr << "Inset type '" << name <<
1788 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1792 case LFUN_CITATION_INSERT: {
1793 if (argument.empty()) {
1794 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1797 // we can have one optional argument, delimited by '|'
1798 // citation-insert <key>|<text_before>
1799 // this should be enhanced to also support text_after
1800 // and citation style
1801 string arg = argument;
1803 if (contains(argument, "|")) {
1804 arg = token(argument, '|', 0);
1805 opt1 = token(argument, '|', 1);
1807 InsetCommandParams icp(CITE_CODE);
1808 icp["key"] = from_utf8(arg);
1810 icp["before"] = from_utf8(opt1);
1811 string icstr = InsetCommand::params2string("citation", icp);
1812 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1817 case LFUN_INSET_APPLY: {
1818 string const name = cmd.getArg(0);
1819 Inset * inset = editedInset(name);
1821 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1825 // put cursor in front of inset.
1826 if (!setCursorFromInset(inset)) {
1827 LASSERT(false, break);
1830 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1831 inset->dispatch(cur, fr);
1832 dr.update(Update::SinglePar | Update::FitCursor);
1841 buffer_.undo().endUndoGroup();
1842 dr.dispatched(dispatched);
1847 docstring const BufferView::requestSelection()
1849 Cursor & cur = d->cursor_;
1851 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1852 if (!cur.selection()) {
1853 d->xsel_cache_.set = false;
1857 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1858 if (!d->xsel_cache_.set ||
1859 cur.top() != d->xsel_cache_.cursor ||
1860 cur.realAnchor().top() != d->xsel_cache_.anchor)
1862 d->xsel_cache_.cursor = cur.top();
1863 d->xsel_cache_.anchor = cur.realAnchor().top();
1864 d->xsel_cache_.set = cur.selection();
1865 return cur.selectionAsString(false);
1871 void BufferView::clearSelection()
1873 d->cursor_.clearSelection();
1874 // Clear the selection buffer. Otherwise a subsequent
1875 // middle-mouse-button paste would use the selection buffer,
1876 // not the more current external selection.
1877 cap::clearSelection();
1878 d->xsel_cache_.set = false;
1879 // The buffer did not really change, but this causes the
1880 // redraw we need because we cleared the selection above.
1881 buffer_.changed(false);
1885 void BufferView::resize(int width, int height)
1887 // Update from work area
1891 // Clear the paragraph height cache.
1892 d->par_height_.clear();
1893 // Redo the metrics.
1898 Inset const * BufferView::getCoveringInset(Text const & text,
1901 TextMetrics & tm = d->text_metrics_[&text];
1902 Inset * inset = tm.checkInsetHit(x, y);
1906 if (!inset->descendable(*this))
1907 // No need to go further down if the inset is not
1911 size_t cell_number = inset->nargs();
1912 // Check all the inner cell.
1913 for (size_t i = 0; i != cell_number; ++i) {
1914 Text const * inner_text = inset->getText(i);
1917 Inset const * inset_deeper =
1918 getCoveringInset(*inner_text, x, y);
1920 return inset_deeper;
1928 void BufferView::updateHoveredInset() const
1930 // Get inset under mouse, if there is one.
1931 Inset const * covering_inset = getCoveringInset(buffer_.text(),
1932 d->mouse_position_cache_.x_, d->mouse_position_cache_.y_);
1933 if (covering_inset == d->last_inset_)
1934 // Same inset, no need to do anything...
1937 bool need_redraw = false;
1939 // Remove the hint on the last hovered inset (if any).
1940 need_redraw |= d->last_inset_->setMouseHover(false);
1942 // const_cast because of setMouseHover().
1943 Inset * inset = const_cast<Inset *>(covering_inset);
1945 // Highlight the newly hovered inset (if any).
1946 need_redraw |= inset->setMouseHover(true);
1948 d->last_inset_ = inset;
1951 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1952 << d->mouse_position_cache_.x_ << ", "
1953 << d->mouse_position_cache_.y_ << ")");
1955 d->update_strategy_ = DecorationUpdate;
1957 // This event (moving without mouse click) is not passed further.
1958 // This should be changed if it is further utilized.
1959 buffer_.changed(false);
1964 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1966 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1968 // This is only called for mouse related events including
1969 // LFUN_FILE_OPEN generated by drag-and-drop.
1970 FuncRequest cmd = cmd0;
1972 Cursor old = cursor();
1974 cur.push(buffer_.inset());
1975 cur.setSelection(d->cursor_.selection());
1977 // Either the inset under the cursor or the
1978 // surrounding Text will handle this event.
1980 // make sure we stay within the screen...
1981 cmd.set_y(min(max(cmd.y(), -1), height_));
1983 d->mouse_position_cache_.x_ = cmd.x();
1984 d->mouse_position_cache_.y_ = cmd.y();
1986 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1987 updateHoveredInset();
1991 // Build temporary cursor.
1992 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
1994 // Put anchor at the same position.
1997 cur.beginUndoGroup();
1999 // Try to dispatch to an non-editable inset near this position
2000 // via the temp cursor. If the inset wishes to change the real
2001 // cursor it has to do so explicitly by using
2002 // cur.bv().cursor() = cur; (or similar)
2004 inset->dispatch(cur, cmd);
2006 // Now dispatch to the temporary cursor. If the real cursor should
2007 // be modified, the inset's dispatch has to do so explicitly.
2008 if (!inset || !cur.result().dispatched())
2013 // Notify left insets
2016 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2018 cursor().fixIfBroken();
2021 // Do we have a selection?
2022 theSelection().haveSelection(cursor().selection());
2024 // If the command has been dispatched,
2025 if (cur.result().dispatched() || cur.result().update())
2026 processUpdateFlags(cur.result().update());
2030 void BufferView::lfunScroll(FuncRequest const & cmd)
2032 string const scroll_type = cmd.getArg(0);
2033 int scroll_step = 0;
2034 if (scroll_type == "line")
2035 scroll_step = d->scrollbarParameters_.single_step;
2036 else if (scroll_type == "page")
2037 scroll_step = d->scrollbarParameters_.page_step;
2040 string const scroll_quantity = cmd.getArg(1);
2041 if (scroll_quantity == "up")
2042 scrollUp(scroll_step);
2043 else if (scroll_quantity == "down")
2044 scrollDown(scroll_step);
2046 int const scroll_value = convert<int>(scroll_quantity);
2048 scroll(scroll_step * scroll_value);
2050 buffer_.changed(true);
2051 updateHoveredInset();
2055 int BufferView::minVisiblePart()
2057 return 2 * defaultRowHeight();
2061 int BufferView::scroll(int y)
2064 return scrollDown(y);
2066 return scrollUp(-y);
2071 int BufferView::scrollDown(int offset)
2073 Text * text = &buffer_.text();
2074 TextMetrics & tm = d->text_metrics_[text];
2075 int const ymax = height_ + offset;
2077 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2078 int bottom_pos = last.second->position() + last.second->descent();
2079 if (lyxrc.scroll_below_document)
2080 bottom_pos += height_ - minVisiblePart();
2081 if (last.first + 1 == int(text->paragraphs().size())) {
2082 if (bottom_pos <= height_)
2084 offset = min(offset, bottom_pos - height_);
2087 if (bottom_pos > ymax)
2089 tm.newParMetricsDown();
2091 d->anchor_ypos_ -= offset;
2096 int BufferView::scrollUp(int offset)
2098 Text * text = &buffer_.text();
2099 TextMetrics & tm = d->text_metrics_[text];
2100 int ymin = - offset;
2102 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2103 int top_pos = first.second->position() - first.second->ascent();
2104 if (first.first == 0) {
2107 offset = min(offset, - top_pos);
2112 tm.newParMetricsUp();
2114 d->anchor_ypos_ += offset;
2119 void BufferView::setCursorFromRow(int row)
2124 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2128 buffer_.text().setCursor(d->cursor_, 0, 0);
2130 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
2135 bool BufferView::setCursorFromInset(Inset const * inset)
2137 // are we already there?
2138 if (cursor().nextInset() == inset)
2141 // Inset is not at cursor position. Find it in the document.
2144 while (cur && cur.nextInset() != inset)
2155 void BufferView::gotoLabel(docstring const & label)
2157 std::vector<Buffer const *> bufs = buffer().allRelatives();
2158 std::vector<Buffer const *>::iterator it = bufs.begin();
2159 for (; it != bufs.end(); ++it) {
2160 Buffer const * buf = *it;
2163 Toc & toc = buf->tocBackend().toc("label");
2164 TocIterator toc_it = toc.begin();
2165 TocIterator end = toc.end();
2166 for (; toc_it != end; ++toc_it) {
2167 if (label == toc_it->str()) {
2168 lyx::dispatch(toc_it->action());
2176 TextMetrics const & BufferView::textMetrics(Text const * t) const
2178 return const_cast<BufferView *>(this)->textMetrics(t);
2182 TextMetrics & BufferView::textMetrics(Text const * t)
2184 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2185 if (tmc_it == d->text_metrics_.end()) {
2186 tmc_it = d->text_metrics_.insert(
2187 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2189 return tmc_it->second;
2193 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2196 return textMetrics(t).parMetrics(pit);
2200 int BufferView::workHeight() const
2206 void BufferView::setCursor(DocIterator const & dit)
2209 size_t const n = dit.depth();
2210 for (size_t i = 0; i < n; ++i)
2211 dit[i].inset().edit(d->cursor_, true);
2213 d->cursor_.setCursor(dit);
2214 d->cursor_.setSelection(false);
2218 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2220 // Would be wrong to delete anything if we have a selection.
2221 if (cur.selection())
2224 bool need_anchor_change = false;
2225 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2226 need_anchor_change);
2228 if (need_anchor_change)
2236 buffer_.updateBuffer();
2237 buffer_.changed(true);
2242 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2244 LASSERT(&cur.bv() == this, /**/);
2247 // this event will clear selection so we save selection for
2248 // persistent selection
2249 cap::saveSelection(cursor());
2251 d->cursor_.macroModeClose();
2253 // Has the cursor just left the inset?
2254 bool leftinset = (&d->cursor_.inset() != &cur.inset());
2256 d->cursor_.fixIfBroken();
2258 // FIXME: shift-mouse selection doesn't work well across insets.
2259 bool do_selection = select && &d->cursor_.normalAnchor().inset() == &cur.inset();
2261 // do the dEPM magic if needed
2262 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2263 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2264 // the leftinset bool would not be necessary (badcursor instead).
2265 bool update = leftinset;
2266 if (!do_selection && d->cursor_.inTexted())
2267 update |= checkDepm(cur, d->cursor_);
2270 d->cursor_.resetAnchor();
2271 d->cursor_.setCursor(cur);
2272 d->cursor_.boundary(cur.boundary());
2274 d->cursor_.setSelection();
2276 d->cursor_.clearSelection();
2278 d->cursor_.finishUndo();
2279 d->cursor_.setCurrentFont();
2284 void BufferView::putSelectionAt(DocIterator const & cur,
2285 int length, bool backwards)
2287 d->cursor_.clearSelection();
2293 d->cursor_.pos() += length;
2294 d->cursor_.setSelection(d->cursor_, -length);
2296 d->cursor_.setSelection(d->cursor_, length);
2298 // Ensure a redraw happens in any case because the new selection could
2299 // possibly be on the same screen as the previous selection.
2300 processUpdateFlags(Update::Force | Update::FitCursor);
2304 Cursor & BufferView::cursor()
2310 Cursor const & BufferView::cursor() const
2316 pit_type BufferView::anchor_ref() const
2318 return d->anchor_pit_;
2322 bool BufferView::singleParUpdate()
2324 Text & buftext = buffer_.text();
2325 pit_type const bottom_pit = d->cursor_.bottom().pit();
2326 TextMetrics & tm = textMetrics(&buftext);
2327 int old_height = tm.parMetrics(bottom_pit).height();
2329 // make sure inline completion pointer is ok
2330 if (d->inlineCompletionPos_.fixIfBroken())
2331 d->inlineCompletionPos_ = DocIterator();
2333 // In Single Paragraph mode, rebreak only
2334 // the (main text, not inset!) paragraph containing the cursor.
2335 // (if this paragraph contains insets etc., rebreaking will
2336 // recursively descend)
2337 tm.redoParagraph(bottom_pit);
2338 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2339 if (pm.height() != old_height)
2340 // Paragraph height has changed so we cannot proceed to
2341 // the singlePar optimisation.
2344 d->update_strategy_ = SingleParUpdate;
2346 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2347 << " y2: " << pm.position() + pm.descent()
2348 << " pit: " << bottom_pit
2349 << " singlepar: 1");
2354 void BufferView::updateMetrics()
2356 if (height_ == 0 || width_ == 0)
2359 Text & buftext = buffer_.text();
2360 pit_type const npit = int(buftext.paragraphs().size());
2362 // Clear out the position cache in case of full screen redraw,
2363 d->coord_cache_.clear();
2365 // Clear out paragraph metrics to avoid having invalid metrics
2366 // in the cache from paragraphs not relayouted below
2367 // The complete text metrics will be redone.
2368 d->text_metrics_.clear();
2370 TextMetrics & tm = textMetrics(&buftext);
2372 // make sure inline completion pointer is ok
2373 if (d->inlineCompletionPos_.fixIfBroken())
2374 d->inlineCompletionPos_ = DocIterator();
2376 if (d->anchor_pit_ >= npit)
2377 // The anchor pit must have been deleted...
2378 d->anchor_pit_ = npit - 1;
2380 // Rebreak anchor paragraph.
2381 tm.redoParagraph(d->anchor_pit_);
2382 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2385 if (d->anchor_pit_ == 0) {
2386 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2388 // Complete buffer visible? Then it's easy.
2389 if (scrollRange == 0)
2390 d->anchor_ypos_ = anchor_pm.ascent();
2392 // FIXME: Some clever handling needed to show
2393 // the _first_ paragraph up to the top if the cursor is
2394 // in the first line.
2396 anchor_pm.setPosition(d->anchor_ypos_);
2398 LYXERR(Debug::PAINTING, "metrics: "
2399 << " anchor pit = " << d->anchor_pit_
2400 << " anchor ypos = " << d->anchor_ypos_);
2402 // Redo paragraphs above anchor if necessary.
2403 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2404 // We are now just above the anchor paragraph.
2405 pit_type pit1 = d->anchor_pit_ - 1;
2406 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2407 tm.redoParagraph(pit1);
2408 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2410 // Save the paragraph position in the cache.
2415 // Redo paragraphs below the anchor if necessary.
2416 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2417 // We are now just below the anchor paragraph.
2418 pit_type pit2 = d->anchor_pit_ + 1;
2419 for (; pit2 < npit && y2 <= height_; ++pit2) {
2420 tm.redoParagraph(pit2);
2421 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2423 // Save the paragraph position in the cache.
2428 LYXERR(Debug::PAINTING, "Metrics: "
2429 << " anchor pit = " << d->anchor_pit_
2430 << " anchor ypos = " << d->anchor_ypos_
2433 << " pit1 = " << pit1
2434 << " pit2 = " << pit2);
2436 d->update_strategy_ = FullScreenUpdate;
2438 if (lyxerr.debugging(Debug::WORKAREA)) {
2439 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2440 d->coord_cache_.dump();
2445 void BufferView::insertLyXFile(FileName const & fname)
2447 LASSERT(d->cursor_.inTexted(), /**/);
2449 // Get absolute path of file and add ".lyx"
2450 // to the filename if necessary
2451 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2453 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2454 // emit message signal.
2455 message(bformat(_("Inserting document %1$s..."), disp_fn));
2458 Buffer buf("", false);
2459 if (buf.loadLyXFile(filename)) {
2460 ErrorList & el = buffer_.errorList("Parse");
2461 // Copy the inserted document error list into the current buffer one.
2462 el = buf.errorList("Parse");
2463 buffer_.undo().recordUndo(d->cursor_);
2464 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2465 buf.params().documentClassPtr(), el);
2466 res = _("Document %1$s inserted.");
2468 res = _("Could not insert document %1$s");
2471 buffer_.changed(true);
2472 // emit message signal.
2473 message(bformat(res, disp_fn));
2474 buffer_.errors("Parse");
2478 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2484 // Addup contribution of nested insets, from inside to outside,
2485 // keeping the outer paragraph for a special handling below
2486 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2487 CursorSlice const & sl = dit[i];
2491 // get relative position inside sl.inset()
2492 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2494 // Make relative position inside of the edited inset relative to sl.inset()
2498 // In case of an RTL inset, the edited inset will be positioned to the left
2501 bool boundary_i = boundary && i + 1 == dit.depth();
2502 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2507 // remember width for the case that sl.inset() is positioned in an RTL inset
2508 if (i && dit[i - 1].text()) {
2509 // If this Inset is inside a Text Inset, retrieve the Dimension
2510 // from the containing text instead of using Inset::dimension() which
2511 // might not be implemented.
2512 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2513 // elimination of Inset::dim_ cache. This coordOffset() method needs
2514 // to be rewritten in light of the new design.
2515 Dimension const & dim = parMetrics(dit[i - 1].text(),
2516 dit[i - 1].pit()).insetDimension(&sl.inset());
2519 Dimension const dim = sl.inset().dimension(*this);
2523 //lyxerr << "Cursor::getPos, i: "
2524 // << i << " x: " << xx << " y: " << y << endl;
2527 // Add contribution of initial rows of outermost paragraph
2528 CursorSlice const & sl = dit[0];
2529 TextMetrics const & tm = textMetrics(sl.text());
2530 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2531 LASSERT(!pm.rows().empty(), /**/);
2532 y -= pm.rows()[0].ascent();
2534 // FIXME: document this mess
2536 if (sl.pos() > 0 && dit.depth() == 1) {
2538 if (pos && boundary)
2540 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2541 rend = pm.pos2row(pos);
2543 rend = pm.pos2row(sl.pos());
2545 size_t rend = pm.pos2row(sl.pos());
2547 for (size_t rit = 0; rit != rend; ++rit)
2548 y += pm.rows()[rit].height();
2549 y += pm.rows()[rend].ascent();
2551 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2553 // Make relative position from the nested inset now bufferview absolute.
2554 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2557 // In the RTL case place the nested inset at the left of the cursor in
2558 // the outer paragraph
2559 bool boundary_1 = boundary && 1 == dit.depth();
2560 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2568 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2570 if (!paragraphVisible(dit))
2571 return Point(-1, -1);
2573 CursorSlice const & bot = dit.bottom();
2574 TextMetrics const & tm = textMetrics(bot.text());
2576 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2577 p.y_ += tm.parMetrics(bot.pit()).position();
2582 bool BufferView::paragraphVisible(DocIterator const & dit) const
2584 CursorSlice const & bot = dit.bottom();
2585 TextMetrics const & tm = textMetrics(bot.text());
2587 return tm.contains(bot.pit());
2591 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2593 Cursor const & cur = cursor();
2594 Font const font = cur.getFont();
2595 frontend::FontMetrics const & fm = theFontMetrics(font);
2596 int const asc = fm.maxAscent();
2597 int const des = fm.maxDescent();
2599 p = getPos(cur, cur.boundary());
2604 bool BufferView::cursorInView(Point const & p, int h) const
2606 Cursor const & cur = cursor();
2607 // does the cursor touch the screen ?
2608 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2614 void BufferView::draw(frontend::Painter & pain)
2616 if (height_ == 0 || width_ == 0)
2618 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2620 Text & text = buffer_.text();
2621 TextMetrics const & tm = d->text_metrics_[&text];
2622 int const y = tm.first().second->position();
2623 PainterInfo pi(this, pain);
2625 switch (d->update_strategy_) {
2627 case NoScreenUpdate:
2628 // If no screen painting is actually needed, only some the different
2629 // coordinates of insets and paragraphs needs to be updated.
2630 pi.full_repaint = true;
2631 pi.pain.setDrawingEnabled(false);
2635 case SingleParUpdate:
2636 pi.full_repaint = false;
2637 // In general, only the current row of the outermost paragraph
2638 // will be redrawn. Particular cases where selection spans
2639 // multiple paragraph are correctly detected in TextMetrics.
2643 case DecorationUpdate:
2644 // FIXME: We should also distinguish DecorationUpdate to avoid text
2645 // drawing if possible. This is not possible to do easily right now
2646 // because of the single backing pixmap.
2648 case FullScreenUpdate:
2649 // The whole screen, including insets, will be refreshed.
2650 pi.full_repaint = true;
2652 // Clear background.
2653 pain.fillRectangle(0, 0, width_, height_,
2654 pi.backgroundColor(&buffer_.inset()));
2659 // and possibly grey out below
2660 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2661 int const y2 = lastpm.second->position() + lastpm.second->descent();
2664 Color color = buffer().isInternal()
2665 ? Color_background : Color_bottomarea;
2666 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2670 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2672 // The scrollbar needs an update.
2675 // Normalize anchor for next time
2676 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2677 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2678 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2679 ParagraphMetrics const & pm = tm.parMetrics(pit);
2680 if (pm.position() + pm.descent() > 0) {
2681 d->anchor_pit_ = pit;
2682 d->anchor_ypos_ = pm.position();
2686 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2687 << " anchor ypos = " << d->anchor_ypos_);
2691 void BufferView::message(docstring const & msg)
2694 d->gui_->message(msg);
2698 void BufferView::showDialog(string const & name)
2701 d->gui_->showDialog(name, string());
2705 void BufferView::showDialog(string const & name,
2706 string const & data, Inset * inset)
2709 d->gui_->showDialog(name, data, inset);
2713 void BufferView::updateDialog(string const & name, string const & data)
2716 d->gui_->updateDialog(name, data);
2720 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2726 // FIXME: Move this out of BufferView again
2727 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2729 if (!fname.isReadableFile()) {
2730 docstring const error = from_ascii(strerror(errno));
2731 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2732 docstring const text =
2733 bformat(_("Could not read the specified document\n"
2734 "%1$s\ndue to the error: %2$s"), file, error);
2735 Alert::error(_("Could not read file"), text);
2739 if (!fname.isReadableFile()) {
2740 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2741 docstring const text =
2742 bformat(_("%1$s\n is not readable."), file);
2743 Alert::error(_("Could not open file"), text);
2747 // FIXME UNICODE: We don't know the encoding of the file
2748 docstring file_content = fname.fileContents("UTF-8");
2749 if (file_content.empty()) {
2750 Alert::error(_("Reading not UTF-8 encoded file"),
2751 _("The file is not UTF-8 encoded.\n"
2752 "It will be read as local 8Bit-encoded.\n"
2753 "If this does not give the correct result\n"
2754 "then please change the encoding of the file\n"
2755 "to UTF-8 with a program other than LyX.\n"));
2756 file_content = fname.fileContents("local8bit");
2759 return normalize_c(file_content);
2763 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2765 docstring const tmpstr = contentsOfPlaintextFile(f);
2770 Cursor & cur = cursor();
2771 cap::replaceSelection(cur);
2772 buffer_.undo().recordUndo(cur);
2774 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2776 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2778 buffer_.changed(true);
2782 docstring const & BufferView::inlineCompletion() const
2784 return d->inlineCompletion_;
2788 size_t const & BufferView::inlineCompletionUniqueChars() const
2790 return d->inlineCompletionUniqueChars_;
2794 DocIterator const & BufferView::inlineCompletionPos() const
2796 return d->inlineCompletionPos_;
2800 bool samePar(DocIterator const & a, DocIterator const & b)
2802 if (a.empty() && b.empty())
2804 if (a.empty() || b.empty())
2806 if (a.depth() != b.depth())
2808 return &a.innerParagraph() == &b.innerParagraph();
2812 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2813 docstring const & completion, size_t uniqueChars)
2815 uniqueChars = min(completion.size(), uniqueChars);
2816 bool changed = d->inlineCompletion_ != completion
2817 || d->inlineCompletionUniqueChars_ != uniqueChars;
2818 bool singlePar = true;
2819 d->inlineCompletion_ = completion;
2820 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2822 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2825 DocIterator const & old = d->inlineCompletionPos_;
2827 //lyxerr << "inlineCompletionPos changed" << std::endl;
2828 // old or pos are in another paragraph?
2829 if ((!samePar(cur, pos) && !pos.empty())
2830 || (!samePar(cur, old) && !old.empty())) {
2832 //lyxerr << "different paragraph" << std::endl;
2834 d->inlineCompletionPos_ = pos;
2839 if (singlePar && !(cur.result().update() & Update::Force))
2840 cur.updateFlags(cur.result().update() | Update::SinglePar);
2842 cur.updateFlags(cur.result().update() | Update::Force);