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"
42 #include "MetricsInfo.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
49 #include "TextClass.h"
50 #include "TextMetrics.h"
52 #include "TocBackend.h"
54 #include "WordLangTuple.h"
56 #include "insets/InsetBibtex.h"
57 #include "insets/InsetCommand.h" // ChangeRefs
58 #include "insets/InsetExternal.h"
59 #include "insets/InsetGraphics.h"
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62 #include "insets/InsetNote.h"
64 #include "frontends/alert.h"
65 #include "frontends/Application.h"
66 #include "frontends/Delegates.h"
67 #include "frontends/FontMetrics.h"
68 #include "frontends/Painter.h"
69 #include "frontends/Selection.h"
71 #include "graphics/Previews.h"
73 #include "support/convert.h"
74 #include "support/debug.h"
75 #include "support/ExceptionMessage.h"
76 #include "support/filetools.h"
77 #include "support/gettext.h"
78 #include "support/lstrings.h"
79 #include "support/Package.h"
80 #include "support/types.h"
89 using namespace lyx::support;
93 namespace Alert = frontend::Alert;
97 /// Return an inset of this class if it exists at the current cursor position
99 T * getInsetByCode(Cursor const & cur, InsetCode code)
101 DocIterator it = cur;
102 Inset * inset = it.nextInset();
103 if (inset && inset->lyxCode() == code)
104 return static_cast<T*>(inset);
109 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
112 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
113 docstring const & contents)
115 DocIterator tmpdit = dit;
118 Inset const * inset = tmpdit.nextInset();
120 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
121 && (contents.empty() ||
122 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
126 tmpdit.forwardInset();
133 /// Looks for next inset with one of the given codes.
134 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
138 DocIterator tmpdit = dit;
139 tmpdit.forwardInset();
144 Inset const * inset = tmpdit.nextInset();
146 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
147 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
151 if (!findNextInset(tmpdit, codes, contents)) {
152 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
153 Inset * inset = &tmpdit.bottom().inset();
154 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
155 if (!findNextInset(tmpdit, codes, contents))
167 /// Looks for next inset with the given code
168 void findInset(DocIterator & dit, InsetCode code, bool same_content)
170 findInset(dit, vector<InsetCode>(1, code), same_content);
174 /// Moves cursor to the next inset with one of the given codes.
175 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
178 Cursor tmpcur = bv->cursor();
179 if (!findInset(tmpcur, codes, same_content)) {
180 bv->cursor().message(_("No more insets"));
184 tmpcur.clearSelection();
185 bv->setCursor(tmpcur);
190 /// Moves cursor to the next inset with given code.
191 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
193 gotoInset(bv, vector<InsetCode>(1, code), same_content);
197 /// A map from a Text to the associated text metrics
198 typedef map<Text const *, TextMetrics> TextMetricsCache;
200 enum ScreenUpdateStrategy {
210 /////////////////////////////////////////////////////////////////////
214 /////////////////////////////////////////////////////////////////////
216 struct BufferView::Private
218 Private(BufferView & bv): wh_(0), cursor_(bv),
219 anchor_pit_(0), anchor_ypos_(0),
220 inlineCompletionUniqueChars_(0),
221 last_inset_(0), gui_(0)
225 ScrollbarParameters scrollbarParameters_;
227 ScreenUpdateStrategy update_strategy_;
229 CoordCache coord_cache_;
231 /// Estimated average par height for scrollbar.
233 /// this is used to handle XSelection events in the right manner.
242 pit_type anchor_pit_;
246 vector<int> par_height_;
249 DocIterator inlineCompletionPos_;
251 docstring inlineCompletion_;
253 size_t inlineCompletionUniqueChars_;
255 /// keyboard mapping object.
258 /// last visited inset.
259 /** kept to send setMouseHover(false).
260 * Not owned, so don't delete.
264 mutable TextMetricsCache text_metrics_;
267 /** Not owned, so don't delete.
269 frontend::GuiBufferViewDelegate * gui_;
271 /// Cache for Find Next
272 FuncRequest search_request_cache_;
276 BufferView::BufferView(Buffer & buf)
277 : width_(0), height_(0), full_screen_(false), buffer_(buf),
278 d(new Private(*this))
280 d->xsel_cache_.set = false;
281 d->intl_.initKeyMapper(lyxrc.use_kbmap);
283 d->cursor_.setBuffer(&buf);
284 d->cursor_.push(buffer_.inset());
285 d->cursor_.resetAnchor();
286 d->cursor_.setCurrentFont();
288 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
289 thePreviews().generateBufferPreviews(buffer_);
293 BufferView::~BufferView()
295 // current buffer is going to be switched-off, save cursor pos
296 // Ideally, the whole cursor stack should be saved, but session
297 // currently can only handle bottom (whole document) level pit and pos.
298 // That is to say, if a cursor is in a nested inset, it will be
299 // restore to the left of the top level inset.
300 LastFilePosSection::FilePos fp;
301 fp.pit = d->cursor_.bottom().pit();
302 fp.pos = d->cursor_.bottom().pos();
303 theSession().lastFilePos().save(buffer_.fileName(), fp);
309 int BufferView::rightMargin() const
311 // The additional test for the case the outliner is opened.
313 !lyxrc.full_screen_limit ||
314 width_ < lyxrc.full_screen_width + 20)
317 return (width_ - lyxrc.full_screen_width) / 2;
321 int BufferView::leftMargin() const
323 return rightMargin();
327 bool BufferView::isTopScreen() const
329 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
333 bool BufferView::isBottomScreen() const
335 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
339 Intl & BufferView::getIntl()
345 Intl const & BufferView::getIntl() const
351 CoordCache & BufferView::coordCache()
353 return d->coord_cache_;
357 CoordCache const & BufferView::coordCache() const
359 return d->coord_cache_;
363 Buffer & BufferView::buffer()
369 Buffer const & BufferView::buffer() const
375 bool BufferView::fitCursor()
377 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
378 frontend::FontMetrics const & fm =
379 theFontMetrics(d->cursor_.getFont().fontInfo());
380 int const asc = fm.maxAscent();
381 int const des = fm.maxDescent();
382 Point const p = getPos(d->cursor_, d->cursor_.boundary());
383 if (p.y_ - asc >= 0 && p.y_ + des < height_)
390 void BufferView::processUpdateFlags(Update::flags flags)
392 // last_inset_ points to the last visited inset. This pointer may become
393 // invalid because of keyboard editing. Since all such operations
394 // causes screen update(), I reset last_inset_ to avoid such a problem.
396 // This is close to a hot-path.
397 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
398 << "[fitcursor = " << (flags & Update::FitCursor)
399 << ", forceupdate = " << (flags & Update::Force)
400 << ", singlepar = " << (flags & Update::SinglePar)
401 << "] buffer: " << &buffer_);
403 buffer_.updateMacros();
405 // Now do the first drawing step if needed. This consists on updating
406 // the CoordCache in updateMetrics().
407 // The second drawing step is done in WorkArea::redraw() if needed.
409 // Case when no explicit update is requested.
411 // no need to redraw anything.
412 d->update_strategy_ = NoScreenUpdate;
416 if (flags == Update::Decoration) {
417 d->update_strategy_ = DecorationUpdate;
422 if (flags == Update::FitCursor
423 || flags == (Update::Decoration | Update::FitCursor)) {
424 // tell the frontend to update the screen if needed.
429 if (flags & Update::Decoration) {
430 d->update_strategy_ = DecorationUpdate;
434 // no screen update is needed.
435 d->update_strategy_ = NoScreenUpdate;
439 bool const full_metrics = flags & Update::Force || !singleParUpdate();
442 // We have to update the full screen metrics.
445 if (!(flags & Update::FitCursor)) {
446 // Nothing to do anymore. Trigger a redraw and return
451 // updateMetrics() does not update paragraph position
452 // This is done at draw() time. So we need a redraw!
456 // The cursor is off screen so ensure it is visible.
463 void BufferView::updateScrollbar()
465 if (height_ == 0 && width_ == 0)
468 // We prefer fixed size line scrolling.
469 d->scrollbarParameters_.single_step = defaultRowHeight();
470 // We prefer full screen page scrolling.
471 d->scrollbarParameters_.page_step = height_;
473 Text & t = buffer_.text();
474 TextMetrics & tm = d->text_metrics_[&t];
476 LYXERR(Debug::GUI, " Updating scrollbar: height: "
477 << t.paragraphs().size()
478 << " curr par: " << d->cursor_.bottom().pit()
479 << " default height " << defaultRowHeight());
481 size_t const parsize = t.paragraphs().size();
482 if (d->par_height_.size() != parsize) {
483 d->par_height_.clear();
484 // FIXME: We assume a default paragraph height of 2 rows. This
485 // should probably be pondered with the screen width.
486 d->par_height_.resize(parsize, defaultRowHeight() * 2);
489 // Look at paragraph heights on-screen
490 pair<pit_type, ParagraphMetrics const *> first = tm.first();
491 pair<pit_type, ParagraphMetrics const *> last = tm.last();
492 for (pit_type pit = first.first; pit <= last.first; ++pit) {
493 d->par_height_[pit] = tm.parMetrics(pit).height();
494 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
495 << d->par_height_[pit]);
498 int top_pos = first.second->position() - first.second->ascent();
499 int bottom_pos = last.second->position() + last.second->descent();
500 bool first_visible = first.first == 0 && top_pos >= 0;
501 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
502 if (first_visible && last_visible) {
503 d->scrollbarParameters_.min = 0;
504 d->scrollbarParameters_.max = 0;
508 d->scrollbarParameters_.min = top_pos;
509 for (size_t i = 0; i != size_t(first.first); ++i)
510 d->scrollbarParameters_.min -= d->par_height_[i];
511 d->scrollbarParameters_.max = bottom_pos;
512 for (size_t i = last.first + 1; i != parsize; ++i)
513 d->scrollbarParameters_.max += d->par_height_[i];
515 d->scrollbarParameters_.position = 0;
516 // The reference is the top position so we remove one page.
517 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
521 ScrollbarParameters const & BufferView::scrollbarParameters() const
523 return d->scrollbarParameters_;
527 docstring BufferView::toolTip(int x, int y) const
529 // Get inset under mouse, if there is one.
530 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
532 // No inset, no tooltip...
534 return covering_inset->toolTip(*this, x, y);
538 docstring BufferView::contextMenu(int x, int y) const
540 //If there is a selection, return the containing inset menu
541 if (d->cursor_.selection())
542 return d->cursor_.inset().contextMenu(*this, x, y);
544 // Get inset under mouse, if there is one.
545 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
547 return covering_inset->contextMenu(*this, x, y);
549 return buffer_.inset().contextMenu(*this, x, y);
553 void BufferView::scrollDocView(int value)
555 int const offset = value - d->scrollbarParameters_.position;
557 // No scrolling at all? No need to redraw anything
561 // If the offset is less than 2 screen height, prefer to scroll instead.
562 if (abs(offset) <= 2 * height_) {
563 d->anchor_ypos_ -= offset;
569 // cut off at the top
570 if (value <= d->scrollbarParameters_.min) {
571 DocIterator dit = doc_iterator_begin(&buffer_);
573 LYXERR(Debug::SCROLLING, "scroll to top");
577 // cut off at the bottom
578 if (value >= d->scrollbarParameters_.max) {
579 DocIterator dit = doc_iterator_end(&buffer_);
582 LYXERR(Debug::SCROLLING, "scroll to bottom");
586 // find paragraph at target position
587 int par_pos = d->scrollbarParameters_.min;
589 for (; i != int(d->par_height_.size()); ++i) {
590 par_pos += d->par_height_[i];
591 if (par_pos >= value)
595 if (par_pos < value) {
596 // It seems we didn't find the correct pit so stay on the safe side and
598 LYXERR0("scrolling position not found!");
599 scrollDocView(d->scrollbarParameters_.max);
603 DocIterator dit = doc_iterator_begin(&buffer_);
605 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
610 // FIXME: this method is not working well.
611 void BufferView::setCursorFromScrollbar()
613 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
615 int const height = 2 * defaultRowHeight();
616 int const first = height;
617 int const last = height_ - height;
619 Cursor const & oldcur = d->cursor_;
621 switch (cursorStatus(oldcur)) {
629 int const y = getPos(oldcur, oldcur.boundary()).y_;
630 newy = min(last, max(y, first));
634 // We reset the cursor because cursorStatus() does not
635 // work when the cursor is within mathed.
637 cur.reset(buffer_.inset());
638 tm.setCursorFromCoordinates(cur, 0, newy);
640 // update the bufferview cursor and notify insets
641 // FIXME: Care about the d->cursor_ flags to redraw if needed
642 Cursor old = d->cursor_;
644 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
646 d->cursor_.fixIfBroken();
650 Change const BufferView::getCurrentChange() const
652 if (!d->cursor_.selection())
653 return Change(Change::UNCHANGED);
655 DocIterator dit = d->cursor_.selectionBegin();
656 return dit.paragraph().lookupChange(dit.pos());
660 // this could be used elsewhere as well?
661 // FIXME: This does not work within mathed!
662 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
664 Point const p = getPos(dit, dit.boundary());
667 if (p.y_ > workHeight())
673 void BufferView::saveBookmark(unsigned int idx)
675 // tenatively save bookmark, id and pos will be used to
676 // acturately locate a bookmark in a 'live' lyx session.
677 // pit and pos will be updated with bottom level pit/pos
679 theSession().bookmarks().save(
681 d->cursor_.bottom().pit(),
682 d->cursor_.bottom().pos(),
683 d->cursor_.paragraph().id(),
688 // emit message signal.
689 message(_("Save bookmark"));
693 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
694 int top_id, pos_type top_pos)
696 bool success = false;
699 d->cursor_.clearSelection();
701 // if a valid par_id is given, try it first
702 // This is the case for a 'live' bookmark when unique paragraph ID
703 // is used to track bookmarks.
705 dit = buffer_.getParFromID(top_id);
707 dit.pos() = min(dit.paragraph().size(), top_pos);
708 // Some slices of the iterator may not be
709 // reachable (e.g. closed collapsable inset)
710 // so the dociterator may need to be
711 // shortened. Otherwise, setCursor may crash
712 // lyx when the cursor can not be set to these
714 size_t const n = dit.depth();
715 for (size_t i = 0; i < n; ++i)
716 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
724 // if top_id == 0, or searching through top_id failed
725 // This is the case for a 'restored' bookmark when only bottom
726 // (document level) pit was saved. Because of this, bookmark
727 // restoration is inaccurate. If a bookmark was within an inset,
728 // it will be restored to the left of the outmost inset that contains
730 if (bottom_pit < int(buffer_.paragraphs().size())) {
731 dit = doc_iterator_begin(&buffer_);
733 dit.pit() = bottom_pit;
734 dit.pos() = min(bottom_pos, dit.paragraph().size());
739 // Note: only bottom (document) level pit is set.
741 // set the current font.
742 d->cursor_.setCurrentFont();
743 // To center the screen on this new position we need the
744 // paragraph position which is computed at draw() time.
745 // So we need a redraw!
755 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
757 if (lyxrc.rtl_support) {
758 if (d->cursor_.real_current_font.isRightToLeft()) {
759 if (d->intl_.keymap == Intl::PRIMARY)
760 d->intl_.keyMapSec();
762 if (d->intl_.keymap == Intl::SECONDARY)
763 d->intl_.keyMapPrim();
767 d->intl_.getTransManager().translateAndInsert(c, t, cur);
771 int BufferView::workWidth() const
777 void BufferView::showCursor()
779 showCursor(d->cursor_);
783 void BufferView::showCursor(DocIterator const & dit)
785 // We are not properly started yet, delay until resizing is
790 LYXERR(Debug::SCROLLING, "recentering!");
792 CursorSlice const & bot = dit.bottom();
793 TextMetrics & tm = d->text_metrics_[bot.text()];
795 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
796 int bot_pit = bot.pit();
797 if (bot_pit > max_pit) {
798 // FIXME: Why does this happen?
799 LYXERR0("bottom pit is greater that max pit: "
800 << bot_pit << " > " << max_pit);
804 if (bot_pit == tm.first().first - 1)
805 tm.newParMetricsUp();
806 else if (bot_pit == tm.last().first + 1)
807 tm.newParMetricsDown();
809 if (tm.contains(bot_pit)) {
810 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
811 LASSERT(!pm.rows().empty(), /**/);
812 // FIXME: smooth scrolling doesn't work in mathed.
813 CursorSlice const & cs = dit.innerTextSlice();
814 int offset = coordOffset(dit, dit.boundary()).y_;
815 int ypos = pm.position() + offset;
816 Dimension const & row_dim =
817 pm.getRow(cs.pos(), dit.boundary()).dimension();
819 if (ypos - row_dim.ascent() < 0)
820 scrolled = scrollUp(- ypos + row_dim.ascent());
821 else if (ypos + row_dim.descent() > height_)
822 scrolled = scrollDown(ypos - height_ + row_dim.descent());
823 // else, nothing to do, the cursor is already visible so we just return.
831 // fix inline completion position
832 if (d->inlineCompletionPos_.fixIfBroken())
833 d->inlineCompletionPos_ = DocIterator();
835 tm.redoParagraph(bot_pit);
836 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
837 int offset = coordOffset(dit, dit.boundary()).y_;
839 d->anchor_pit_ = bot_pit;
840 CursorSlice const & cs = dit.innerTextSlice();
841 Dimension const & row_dim =
842 pm.getRow(cs.pos(), dit.boundary()).dimension();
844 if (d->anchor_pit_ == 0)
845 d->anchor_ypos_ = offset + pm.ascent();
846 else if (d->anchor_pit_ == max_pit)
847 d->anchor_ypos_ = height_ - offset - row_dim.descent();
849 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
856 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
860 Cursor & cur = d->cursor_;
862 switch (cmd.action) {
865 flag.setEnabled(buffer_.undo().hasUndoStack());
868 flag.setEnabled(buffer_.undo().hasRedoStack());
870 case LFUN_FILE_INSERT:
871 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
872 case LFUN_FILE_INSERT_PLAINTEXT:
873 case LFUN_BOOKMARK_SAVE:
874 // FIXME: Actually, these LFUNS should be moved to Text
875 flag.setEnabled(cur.inTexted());
877 case LFUN_FONT_STATE:
878 case LFUN_LABEL_INSERT:
879 case LFUN_INFO_INSERT:
880 case LFUN_INSET_EDIT:
881 case LFUN_PARAGRAPH_GOTO:
883 case LFUN_REFERENCE_NEXT:
885 case LFUN_WORD_FINDADV:
886 case LFUN_WORD_REPLACE:
889 case LFUN_MARK_TOGGLE:
890 case LFUN_SCREEN_RECENTER:
891 case LFUN_BIBTEX_DATABASE_ADD:
892 case LFUN_BIBTEX_DATABASE_DEL:
893 case LFUN_NOTES_MUTATE:
894 case LFUN_ALL_INSETS_TOGGLE:
895 case LFUN_STATISTICS:
896 flag.setEnabled(true);
899 // @todo Test if current WorkArea is the search WorkArea
900 case LFUN_REGEXP_MODE:
901 flag.setEnabled(! this->cursor().inRegexped());
904 case LFUN_COPY_LABEL_AS_REF: {
905 // if there is an inset at cursor, see whether it
906 // handles the lfun, other start from scratch
907 Inset * inset = cur.nextInset();
908 if (!inset || !inset->getStatus(cur, cmd, flag))
909 flag = lyx::getStatus(cmd);
913 case LFUN_NEXT_INSET_TOGGLE:
914 case LFUN_NEXT_INSET_MODIFY: {
915 // this is the real function we want to invoke
916 FuncRequest tmpcmd = cmd;
917 tmpcmd.action = (cmd.action == LFUN_NEXT_INSET_TOGGLE)
918 ? LFUN_INSET_TOGGLE : LFUN_INSET_MODIFY;
919 // if there is an inset at cursor, see whether it
920 // handles the lfun, other start from scratch
921 Inset * inset = cur.nextInset();
922 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
923 flag = lyx::getStatus(tmpcmd);
927 case LFUN_LABEL_GOTO: {
928 flag.setEnabled(!cmd.argument().empty()
929 || getInsetByCode<InsetRef>(cur, REF_CODE));
933 case LFUN_CHANGES_TRACK:
934 flag.setEnabled(true);
935 flag.setOnOff(buffer_.params().trackChanges);
938 case LFUN_CHANGES_OUTPUT:
939 flag.setEnabled(true);
940 flag.setOnOff(buffer_.params().outputChanges);
943 case LFUN_CHANGES_MERGE:
944 case LFUN_CHANGE_NEXT:
945 case LFUN_ALL_CHANGES_ACCEPT:
946 case LFUN_ALL_CHANGES_REJECT:
947 // TODO: context-sensitive enabling of LFUNs
948 // In principle, these command should only be enabled if there
949 // is a change in the document. However, without proper
950 // optimizations, this will inevitably result in poor performance.
951 flag.setEnabled(true);
954 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
955 flag.setOnOff(buffer_.params().compressed);
960 case LFUN_SCREEN_DOWN:
962 case LFUN_SCREEN_UP_SELECT:
963 case LFUN_SCREEN_DOWN_SELECT:
964 flag.setEnabled(true);
967 case LFUN_LAYOUT_TABULAR:
968 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
972 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
975 case LFUN_LAYOUT_PARAGRAPH:
976 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
979 case LFUN_INSET_SETTINGS: {
980 InsetCode code = cur.inset().lyxCode();
981 if (cmd.getArg(0) == insetName(code)) {
982 flag.setEnabled(true);
986 InsetCode next_code = cur.nextInset()
987 ? cur.nextInset()->lyxCode() : NO_CODE;
988 //FIXME: remove these special cases:
998 enable = (cmd.argument().empty() ||
999 cmd.getArg(0) == insetName(next_code));
1004 flag.setEnabled(enable);
1008 case LFUN_DIALOG_SHOW_NEW_INSET:
1009 flag.setEnabled(cur.inset().lyxCode() != ERT_CODE &&
1010 cur.inset().lyxCode() != LISTINGS_CODE);
1011 if (cur.inset().lyxCode() == CAPTION_CODE) {
1013 if (cur.inset().getStatus(cur, cmd, flag))
1018 case LFUN_BRANCH_ACTIVATE:
1019 case LFUN_BRANCH_DEACTIVATE: {
1020 bool enable = false;
1021 docstring const branchName = cmd.argument();
1022 if (!branchName.empty())
1023 enable = buffer_.params().branchlist().find(branchName);
1024 flag.setEnabled(enable);
1029 flag.setEnabled(false);
1036 bool BufferView::dispatch(FuncRequest const & cmd)
1038 //lyxerr << [ cmd = " << cmd << "]" << endl;
1040 // Make sure that the cached BufferView is correct.
1041 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1042 << " arg[" << to_utf8(cmd.argument()) << ']'
1043 << " x[" << cmd.x << ']'
1044 << " y[" << cmd.y << ']'
1045 << " button[" << cmd.button() << ']');
1047 Cursor & cur = d->cursor_;
1049 switch (cmd.action) {
1052 cur.message(_("Undo"));
1053 cur.clearSelection();
1054 if (!cur.textUndo())
1055 cur.message(_("No further undo information"));
1057 processUpdateFlags(Update::Force | Update::FitCursor);
1061 cur.message(_("Redo"));
1062 cur.clearSelection();
1063 if (!cur.textRedo())
1064 cur.message(_("No further redo information"));
1066 processUpdateFlags(Update::Force | Update::FitCursor);
1069 case LFUN_FONT_STATE:
1070 cur.message(cur.currentState());
1073 case LFUN_BOOKMARK_SAVE:
1074 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1077 case LFUN_LABEL_GOTO: {
1078 docstring label = cmd.argument();
1079 if (label.empty()) {
1081 getInsetByCode<InsetRef>(d->cursor_, REF_CODE);
1083 label = inset->getParam("reference");
1084 // persistent=false: use temp_bookmark
1093 case LFUN_INSET_EDIT: {
1094 FuncRequest fr(cmd);
1095 // if there is an inset at cursor, see whether it
1097 Inset * inset = cur.nextInset();
1099 inset->dispatch(cur, fr);
1100 // if it did not work, try the underlying inset.
1101 if (!inset || !cur.result().dispatched())
1104 // FIXME I'm adding the last break to solve a crash,
1105 // but that is obviously not right.
1106 if (!cur.result().dispatched())
1107 // It did not work too; no action needed.
1112 case LFUN_PARAGRAPH_GOTO: {
1113 int const id = convert<int>(cmd.getArg(0));
1114 int const pos = convert<int>(cmd.getArg(1));
1116 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1117 b = theBufferList().next(b)) {
1119 DocIterator dit = b->getParFromID(id);
1121 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1125 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1126 << " found in buffer `"
1127 << b->absFileName() << "'.");
1129 if (b == &buffer_) {
1133 processUpdateFlags(Update::Force | Update::FitCursor);
1135 // Switch to other buffer view and resend cmd
1136 theLyXFunc().dispatch(FuncRequest(
1137 LFUN_BUFFER_SWITCH, b->absFileName()));
1138 theLyXFunc().dispatch(cmd);
1145 case LFUN_NOTE_NEXT:
1146 gotoInset(this, NOTE_CODE, false);
1149 case LFUN_REFERENCE_NEXT: {
1150 vector<InsetCode> tmp;
1151 tmp.push_back(LABEL_CODE);
1152 tmp.push_back(REF_CODE);
1153 gotoInset(this, tmp, true);
1157 case LFUN_CHANGES_TRACK:
1158 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1161 case LFUN_CHANGES_OUTPUT:
1162 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1163 if (buffer_.params().outputChanges) {
1164 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1165 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1166 LaTeXFeatures::isAvailable("xcolor");
1168 if (!dvipost && !xcolorsoul) {
1169 Alert::warning(_("Changes not shown in LaTeX output"),
1170 _("Changes will not be highlighted in LaTeX output, "
1171 "because neither dvipost nor xcolor/soul are installed.\n"
1172 "Please install these packages or redefine "
1173 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1174 } else if (!xcolorsoul) {
1175 Alert::warning(_("Changes not shown in LaTeX output"),
1176 _("Changes will not be highlighted in LaTeX output "
1177 "when using pdflatex, because xcolor and soul are not installed.\n"
1178 "Please install both packages or redefine "
1179 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1184 case LFUN_CHANGE_NEXT:
1185 findNextChange(this);
1186 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1187 processUpdateFlags(Update::Force | Update::FitCursor);
1190 case LFUN_CHANGES_MERGE:
1191 if (findNextChange(this)) {
1192 processUpdateFlags(Update::Force | Update::FitCursor);
1193 showDialog("changes");
1197 case LFUN_ALL_CHANGES_ACCEPT:
1198 // select complete document
1199 d->cursor_.reset(buffer_.inset());
1200 d->cursor_.selHandle(true);
1201 buffer_.text().cursorBottom(d->cursor_);
1202 // accept everything in a single step to support atomic undo
1203 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1204 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1205 processUpdateFlags(Update::Force | Update::FitCursor);
1208 case LFUN_ALL_CHANGES_REJECT:
1209 // select complete document
1210 d->cursor_.reset(buffer_.inset());
1211 d->cursor_.selHandle(true);
1212 buffer_.text().cursorBottom(d->cursor_);
1213 // reject everything in a single step to support atomic undo
1214 // Note: reject does not work recursively; the user may have to repeat the operation
1215 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1216 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1217 processUpdateFlags(Update::Force | Update::FitCursor);
1220 case LFUN_WORD_FIND: {
1221 FuncRequest req = cmd;
1222 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1223 req = d->search_request_cache_;
1224 if (req.argument().empty()) {
1225 theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1228 if (find(this, req))
1231 message(_("String not found!"));
1232 d->search_request_cache_ = req;
1236 case LFUN_WORD_REPLACE: {
1237 bool has_deleted = false;
1238 if (cur.selection()) {
1239 DocIterator beg = cur.selectionBegin();
1240 DocIterator end = cur.selectionEnd();
1241 if (beg.pit() == end.pit()) {
1242 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1243 if (cur.paragraph().isDeleted(p))
1248 replace(this, cmd, has_deleted);
1252 case LFUN_WORD_FINDADV:
1257 cur.clearSelection();
1259 cur.message(from_utf8(N_("Mark off")));
1263 cur.clearSelection();
1266 cur.message(from_utf8(N_("Mark on")));
1269 case LFUN_MARK_TOGGLE:
1270 cur.clearSelection();
1273 cur.message(from_utf8(N_("Mark removed")));
1276 cur.message(from_utf8(N_("Mark set")));
1281 case LFUN_SCREEN_RECENTER:
1285 case LFUN_BIBTEX_DATABASE_ADD: {
1286 Cursor tmpcur = d->cursor_;
1287 findInset(tmpcur, BIBTEX_CODE, false);
1288 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1291 if (inset->addDatabase(cmd.argument()))
1292 buffer_.updateBibfilesCache();
1297 case LFUN_BIBTEX_DATABASE_DEL: {
1298 Cursor tmpcur = d->cursor_;
1299 findInset(tmpcur, BIBTEX_CODE, false);
1300 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1303 if (inset->delDatabase(cmd.argument()))
1304 buffer_.updateBibfilesCache();
1309 case LFUN_STATISTICS: {
1310 DocIterator from, to;
1311 if (cur.selection()) {
1312 from = cur.selectionBegin();
1313 to = cur.selectionEnd();
1315 from = doc_iterator_begin(&buffer_);
1316 to = doc_iterator_end(&buffer_);
1318 int const words = countWords(from, to);
1319 int const chars = countChars(from, to, false);
1320 int const chars_blanks = countChars(from, to, true);
1322 if (cur.selection())
1323 message = _("Statistics for the selection:");
1325 message = _("Statistics for the document:");
1328 message += bformat(_("%1$d words"), words);
1330 message += _("One word");
1332 if (chars_blanks != 1)
1333 message += bformat(_("%1$d characters (including blanks)"),
1336 message += _("One character (including blanks)");
1339 message += bformat(_("%1$d characters (excluding blanks)"),
1342 message += _("One character (excluding blanks)");
1344 Alert::information(_("Statistics"), message);
1348 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1349 // turn compression on/off
1350 buffer_.params().compressed = !buffer_.params().compressed;
1352 case LFUN_COPY_LABEL_AS_REF: {
1353 // if there is an inset at cursor, try to copy it
1354 Inset * inset = cur.nextInset();
1356 FuncRequest tmpcmd = cmd;
1357 inset->dispatch(cur, tmpcmd);
1359 if (!cur.result().dispatched())
1360 // It did not work too; no action needed.
1362 cur.clearSelection();
1363 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1366 case LFUN_NEXT_INSET_TOGGLE: {
1367 // create the the real function we want to invoke
1368 FuncRequest tmpcmd = cmd;
1369 tmpcmd.action = LFUN_INSET_TOGGLE;
1370 // if there is an inset at cursor, see whether it
1372 Inset * inset = cur.nextInset();
1374 if (inset->isActive()) {
1375 Cursor tmpcur = cur;
1376 tmpcur.pushBackward(*inset);
1377 inset->dispatch(tmpcur, tmpcmd);
1378 if (tmpcur.result().dispatched())
1381 inset->dispatch(cur, tmpcmd);
1383 // if it did not work, try the underlying inset.
1384 if (!inset || !cur.result().dispatched())
1385 cur.dispatch(tmpcmd);
1387 if (!cur.result().dispatched())
1388 // It did not work too; no action needed.
1390 cur.clearSelection();
1391 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1395 case LFUN_NEXT_INSET_MODIFY: {
1396 // create the the real function we want to invoke
1397 FuncRequest tmpcmd = cmd;
1398 tmpcmd.action = LFUN_INSET_MODIFY;
1399 // if there is an inset at cursor, see whether it
1401 Inset * inset = cur.nextInset();
1404 inset->dispatch(cur, tmpcmd);
1406 // if it did not work, try the underlying inset.
1407 if (!inset || !cur.result().dispatched()) {
1409 cur.dispatch(tmpcmd);
1412 if (!cur.result().dispatched())
1413 // It did not work too; no action needed.
1415 cur.clearSelection();
1416 processUpdateFlags(Update::Force | Update::FitCursor);
1420 case LFUN_SCREEN_UP:
1421 case LFUN_SCREEN_DOWN: {
1422 Point p = getPos(cur, cur.boundary());
1423 if (p.y_ < 0 || p.y_ > height_) {
1424 // The cursor is off-screen so recenter before proceeding.
1426 p = getPos(cur, cur.boundary());
1428 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1429 ? - height_ : height_);
1430 if (cmd.action == LFUN_SCREEN_UP && scrolled > - height_)
1432 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1433 p = Point(width_, height_);
1434 cur.reset(buffer_.inset());
1437 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1438 //FIXME: what to do with cur.x_target()?
1447 case LFUN_SCREEN_UP_SELECT: {
1448 cur.selHandle(true);
1449 if (isTopScreen()) {
1450 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1454 int y = getPos(cur, cur.boundary()).y_;
1455 int const ymin = y - height_ + defaultRowHeight();
1456 while (y > ymin && cur.up())
1457 y = getPos(cur, cur.boundary()).y_;
1460 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1464 case LFUN_SCREEN_DOWN_SELECT: {
1465 cur.selHandle(true);
1466 if (isBottomScreen()) {
1467 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1471 int y = getPos(cur, cur.boundary()).y_;
1472 int const ymax = y + height_ - defaultRowHeight();
1473 while (y < ymax && cur.down())
1474 y = getPos(cur, cur.boundary()).y_;
1477 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1481 case LFUN_BRANCH_ACTIVATE:
1482 case LFUN_BRANCH_DEACTIVATE:
1483 buffer_.dispatch(cmd);
1484 processUpdateFlags(Update::Force);
1487 // This could be rewriten using some command like forall <insetname> <command>
1488 // once the insets refactoring is done.
1489 case LFUN_NOTES_MUTATE: {
1490 if (cmd.argument().empty())
1493 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1494 processUpdateFlags(Update::Force);
1499 case LFUN_ALL_INSETS_TOGGLE: {
1501 string const name = split(to_utf8(cmd.argument()), action, ' ');
1502 InsetCode const inset_code = insetCode(name);
1504 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1506 Inset & inset = cur.buffer()->inset();
1507 InsetIterator it = inset_iterator_begin(inset);
1508 InsetIterator const end = inset_iterator_end(inset);
1509 for (; it != end; ++it) {
1510 if (it->asInsetCollapsable()
1511 && (inset_code == NO_CODE
1512 || inset_code == it->lyxCode())) {
1513 Cursor tmpcur = cur;
1514 tmpcur.pushBackward(*it);
1515 it->dispatch(tmpcur, fr);
1518 processUpdateFlags(Update::Force | Update::FitCursor);
1530 docstring const BufferView::requestSelection()
1532 Cursor & cur = d->cursor_;
1534 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1535 if (!cur.selection()) {
1536 d->xsel_cache_.set = false;
1540 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1541 if (!d->xsel_cache_.set ||
1542 cur.top() != d->xsel_cache_.cursor ||
1543 cur.anchor_.top() != d->xsel_cache_.anchor)
1545 d->xsel_cache_.cursor = cur.top();
1546 d->xsel_cache_.anchor = cur.anchor_.top();
1547 d->xsel_cache_.set = cur.selection();
1548 return cur.selectionAsString(false);
1554 void BufferView::clearSelection()
1556 d->cursor_.clearSelection();
1557 // Clear the selection buffer. Otherwise a subsequent
1558 // middle-mouse-button paste would use the selection buffer,
1559 // not the more current external selection.
1560 cap::clearSelection();
1561 d->xsel_cache_.set = false;
1562 // The buffer did not really change, but this causes the
1563 // redraw we need because we cleared the selection above.
1568 void BufferView::resize(int width, int height)
1570 // Update from work area
1574 // Clear the paragraph height cache.
1575 d->par_height_.clear();
1576 // Redo the metrics.
1581 Inset const * BufferView::getCoveringInset(Text const & text,
1584 TextMetrics & tm = d->text_metrics_[&text];
1585 Inset * inset = tm.checkInsetHit(x, y);
1589 if (!inset->descendable())
1590 // No need to go further down if the inset is not
1594 size_t cell_number = inset->nargs();
1595 // Check all the inner cell.
1596 for (size_t i = 0; i != cell_number; ++i) {
1597 Text const * inner_text = inset->getText(i);
1600 Inset const * inset_deeper =
1601 getCoveringInset(*inner_text, x, y);
1603 return inset_deeper;
1611 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1613 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1615 // This is only called for mouse related events including
1616 // LFUN_FILE_OPEN generated by drag-and-drop.
1617 FuncRequest cmd = cmd0;
1619 Cursor old = cursor();
1621 cur.push(buffer_.inset());
1622 cur.setSelection(d->cursor_.selection());
1624 // Either the inset under the cursor or the
1625 // surrounding Text will handle this event.
1627 // make sure we stay within the screen...
1628 cmd.y = min(max(cmd.y, -1), height_);
1630 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1632 // Get inset under mouse, if there is one.
1633 Inset const * covering_inset =
1634 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1635 if (covering_inset == d->last_inset_)
1636 // Same inset, no need to do anything...
1639 bool need_redraw = false;
1640 // const_cast because of setMouseHover().
1641 Inset * inset = const_cast<Inset *>(covering_inset);
1643 // Remove the hint on the last hovered inset (if any).
1644 need_redraw |= d->last_inset_->setMouseHover(false);
1646 // Highlighted the newly hovered inset (if any).
1647 need_redraw |= inset->setMouseHover(true);
1648 d->last_inset_ = inset;
1652 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1653 << cmd.x << ", " << cmd.y << ")");
1655 d->update_strategy_ = DecorationUpdate;
1657 // This event (moving without mouse click) is not passed further.
1658 // This should be changed if it is further utilized.
1663 // Build temporary cursor.
1664 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1666 // Put anchor at the same position.
1669 cur.beginUndoGroup();
1671 // Try to dispatch to an non-editable inset near this position
1672 // via the temp cursor. If the inset wishes to change the real
1673 // cursor it has to do so explicitly by using
1674 // cur.bv().cursor() = cur; (or similar)
1676 inset->dispatch(cur, cmd);
1678 // Now dispatch to the temporary cursor. If the real cursor should
1679 // be modified, the inset's dispatch has to do so explicitly.
1680 if (!inset || !cur.result().dispatched())
1685 // Notify left insets
1688 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
1690 cursor().fixIfBroken();
1693 // Do we have a selection?
1694 theSelection().haveSelection(cursor().selection());
1696 // If the command has been dispatched,
1697 if (cur.result().dispatched() || cur.result().update())
1698 processUpdateFlags(cur.result().update());
1702 void BufferView::lfunScroll(FuncRequest const & cmd)
1704 string const scroll_type = cmd.getArg(0);
1705 int const scroll_step =
1706 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1707 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1708 if (scroll_step == 0)
1710 string const scroll_quantity = cmd.getArg(1);
1711 if (scroll_quantity == "up")
1712 scrollUp(scroll_step);
1713 else if (scroll_quantity == "down")
1714 scrollDown(scroll_step);
1716 int const scroll_value = convert<int>(scroll_quantity);
1718 scroll(scroll_step * scroll_value);
1725 int BufferView::scroll(int y)
1728 return scrollDown(y);
1730 return scrollUp(-y);
1735 int BufferView::scrollDown(int offset)
1737 Text * text = &buffer_.text();
1738 TextMetrics & tm = d->text_metrics_[text];
1739 int ymax = height_ + offset;
1741 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1742 int bottom_pos = last.second->position() + last.second->descent();
1743 if (last.first + 1 == int(text->paragraphs().size())) {
1744 if (bottom_pos <= height_)
1746 offset = min(offset, bottom_pos - height_);
1749 if (bottom_pos > ymax)
1751 tm.newParMetricsDown();
1753 d->anchor_ypos_ -= offset;
1758 int BufferView::scrollUp(int offset)
1760 Text * text = &buffer_.text();
1761 TextMetrics & tm = d->text_metrics_[text];
1762 int ymin = - offset;
1764 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1765 int top_pos = first.second->position() - first.second->ascent();
1766 if (first.first == 0) {
1769 offset = min(offset, - top_pos);
1774 tm.newParMetricsUp();
1776 d->anchor_ypos_ += offset;
1781 void BufferView::setCursorFromRow(int row)
1786 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1788 d->cursor_.reset(buffer_.inset());
1790 buffer_.text().setCursor(d->cursor_, 0, 0);
1792 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1796 bool BufferView::setCursorFromInset(Inset const * inset)
1798 // are we already there?
1799 if (cursor().nextInset() == inset)
1802 // Inset is not at cursor position. Find it in the document.
1804 cur.reset(buffer().inset());
1805 while (cur && cur.nextInset() != inset)
1816 void BufferView::gotoLabel(docstring const & label)
1818 std::vector<Buffer const *> bufs = buffer().allRelatives();
1819 std::vector<Buffer const *>::iterator it = bufs.begin();
1820 for (; it != bufs.end(); ++it) {
1821 Buffer const * buf = *it;
1824 Toc & toc = buf->tocBackend().toc("label");
1825 TocIterator toc_it = toc.begin();
1826 TocIterator end = toc.end();
1827 for (; toc_it != end; ++toc_it) {
1828 if (label == toc_it->str()) {
1829 dispatch(toc_it->action());
1837 TextMetrics const & BufferView::textMetrics(Text const * t) const
1839 return const_cast<BufferView *>(this)->textMetrics(t);
1843 TextMetrics & BufferView::textMetrics(Text const * t)
1845 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1846 if (tmc_it == d->text_metrics_.end()) {
1847 tmc_it = d->text_metrics_.insert(
1848 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1850 return tmc_it->second;
1854 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1857 return textMetrics(t).parMetrics(pit);
1861 int BufferView::workHeight() const
1867 void BufferView::setCursor(DocIterator const & dit)
1869 size_t const n = dit.depth();
1870 for (size_t i = 0; i < n; ++i)
1871 dit[i].inset().edit(d->cursor_, true);
1873 d->cursor_.setCursor(dit);
1874 d->cursor_.setSelection(false);
1878 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1880 // Would be wrong to delete anything if we have a selection.
1881 if (cur.selection())
1884 bool need_anchor_change = false;
1885 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1886 need_anchor_change);
1888 if (need_anchor_change)
1896 buffer_.updateLabels();
1904 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1906 LASSERT(&cur.bv() == this, /**/);
1909 // this event will clear selection so we save selection for
1910 // persistent selection
1911 cap::saveSelection(cursor());
1913 // Has the cursor just left the inset?
1914 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1916 d->cursor_.fixIfBroken();
1918 // FIXME: shift-mouse selection doesn't work well across insets.
1919 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1921 // do the dEPM magic if needed
1922 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1923 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1924 // the leftinset bool would not be necessary (badcursor instead).
1925 bool update = leftinset;
1926 if (!do_selection && d->cursor_.inTexted())
1927 update |= checkDepm(cur, d->cursor_);
1929 d->cursor_.setCursor(cur);
1930 d->cursor_.boundary(cur.boundary());
1932 d->cursor_.setSelection();
1934 d->cursor_.clearSelection();
1936 d->cursor_.finishUndo();
1937 d->cursor_.setCurrentFont();
1942 void BufferView::putSelectionAt(DocIterator const & cur,
1943 int length, bool backwards)
1945 d->cursor_.clearSelection();
1951 d->cursor_.pos() += length;
1952 d->cursor_.setSelection(d->cursor_, -length);
1954 d->cursor_.setSelection(d->cursor_, length);
1956 // Ensure a redraw happens in any case because the new selection could
1957 // possibly be on the same screen as the previous selection.
1958 processUpdateFlags(Update::Force | Update::FitCursor);
1962 Cursor & BufferView::cursor()
1968 Cursor const & BufferView::cursor() const
1974 pit_type BufferView::anchor_ref() const
1976 return d->anchor_pit_;
1980 bool BufferView::singleParUpdate()
1982 Text & buftext = buffer_.text();
1983 pit_type const bottom_pit = d->cursor_.bottom().pit();
1984 TextMetrics & tm = textMetrics(&buftext);
1985 int old_height = tm.parMetrics(bottom_pit).height();
1987 // make sure inline completion pointer is ok
1988 if (d->inlineCompletionPos_.fixIfBroken())
1989 d->inlineCompletionPos_ = DocIterator();
1991 // In Single Paragraph mode, rebreak only
1992 // the (main text, not inset!) paragraph containing the cursor.
1993 // (if this paragraph contains insets etc., rebreaking will
1994 // recursively descend)
1995 tm.redoParagraph(bottom_pit);
1996 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1997 if (pm.height() != old_height)
1998 // Paragraph height has changed so we cannot proceed to
1999 // the singlePar optimisation.
2002 d->update_strategy_ = SingleParUpdate;
2004 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2005 << " y2: " << pm.position() + pm.descent()
2006 << " pit: " << bottom_pit
2007 << " singlepar: 1");
2012 void BufferView::updateMetrics()
2014 if (height_ == 0 || width_ == 0)
2017 Text & buftext = buffer_.text();
2018 pit_type const npit = int(buftext.paragraphs().size());
2020 // Clear out the position cache in case of full screen redraw,
2021 d->coord_cache_.clear();
2023 // Clear out paragraph metrics to avoid having invalid metrics
2024 // in the cache from paragraphs not relayouted below
2025 // The complete text metrics will be redone.
2026 d->text_metrics_.clear();
2028 TextMetrics & tm = textMetrics(&buftext);
2030 // make sure inline completion pointer is ok
2031 if (d->inlineCompletionPos_.fixIfBroken())
2032 d->inlineCompletionPos_ = DocIterator();
2034 if (d->anchor_pit_ >= npit)
2035 // The anchor pit must have been deleted...
2036 d->anchor_pit_ = npit - 1;
2038 // Rebreak anchor paragraph.
2039 tm.redoParagraph(d->anchor_pit_);
2040 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2043 if (d->anchor_pit_ == 0) {
2044 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2046 // Complete buffer visible? Then it's easy.
2047 if (scrollRange == 0)
2048 d->anchor_ypos_ = anchor_pm.ascent();
2050 // FIXME: Some clever handling needed to show
2051 // the _first_ paragraph up to the top if the cursor is
2052 // in the first line.
2054 anchor_pm.setPosition(d->anchor_ypos_);
2056 LYXERR(Debug::PAINTING, "metrics: "
2057 << " anchor pit = " << d->anchor_pit_
2058 << " anchor ypos = " << d->anchor_ypos_);
2060 // Redo paragraphs above anchor if necessary.
2061 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2062 // We are now just above the anchor paragraph.
2063 pit_type pit1 = d->anchor_pit_ - 1;
2064 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2065 tm.redoParagraph(pit1);
2066 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2068 // Save the paragraph position in the cache.
2073 // Redo paragraphs below the anchor if necessary.
2074 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2075 // We are now just below the anchor paragraph.
2076 pit_type pit2 = d->anchor_pit_ + 1;
2077 for (; pit2 < npit && y2 <= height_; ++pit2) {
2078 tm.redoParagraph(pit2);
2079 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2081 // Save the paragraph position in the cache.
2086 LYXERR(Debug::PAINTING, "Metrics: "
2087 << " anchor pit = " << d->anchor_pit_
2088 << " anchor ypos = " << d->anchor_ypos_
2091 << " pit1 = " << pit1
2092 << " pit2 = " << pit2);
2094 d->update_strategy_ = FullScreenUpdate;
2096 if (lyxerr.debugging(Debug::WORKAREA)) {
2097 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2098 d->coord_cache_.dump();
2103 void BufferView::insertLyXFile(FileName const & fname)
2105 LASSERT(d->cursor_.inTexted(), /**/);
2107 // Get absolute path of file and add ".lyx"
2108 // to the filename if necessary
2109 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2111 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2112 // emit message signal.
2113 message(bformat(_("Inserting document %1$s..."), disp_fn));
2116 Buffer buf("", false);
2117 if (buf.loadLyXFile(filename)) {
2118 ErrorList & el = buffer_.errorList("Parse");
2119 // Copy the inserted document error list into the current buffer one.
2120 el = buf.errorList("Parse");
2121 buffer_.undo().recordUndo(d->cursor_);
2122 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2123 buf.params().documentClassPtr(), el);
2124 res = _("Document %1$s inserted.");
2126 res = _("Could not insert document %1$s");
2131 // emit message signal.
2132 message(bformat(res, disp_fn));
2133 buffer_.errors("Parse");
2137 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2143 // Addup contribution of nested insets, from inside to outside,
2144 // keeping the outer paragraph for a special handling below
2145 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2146 CursorSlice const & sl = dit[i];
2150 // get relative position inside sl.inset()
2151 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2153 // Make relative position inside of the edited inset relative to sl.inset()
2157 // In case of an RTL inset, the edited inset will be positioned to the left
2160 bool boundary_i = boundary && i + 1 == dit.depth();
2161 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2166 // remember width for the case that sl.inset() is positioned in an RTL inset
2167 if (i && dit[i - 1].text()) {
2168 // If this Inset is inside a Text Inset, retrieve the Dimension
2169 // from the containing text instead of using Inset::dimension() which
2170 // might not be implemented.
2171 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2172 // elimination of Inset::dim_ cache. This coordOffset() method needs
2173 // to be rewritten in light of the new design.
2174 Dimension const & dim = parMetrics(dit[i - 1].text(),
2175 dit[i - 1].pit()).insetDimension(&sl.inset());
2178 Dimension const dim = sl.inset().dimension(*this);
2182 //lyxerr << "Cursor::getPos, i: "
2183 // << i << " x: " << xx << " y: " << y << endl;
2186 // Add contribution of initial rows of outermost paragraph
2187 CursorSlice const & sl = dit[0];
2188 TextMetrics const & tm = textMetrics(sl.text());
2189 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2190 LASSERT(!pm.rows().empty(), /**/);
2191 y -= pm.rows()[0].ascent();
2193 // FIXME: document this mess
2195 if (sl.pos() > 0 && dit.depth() == 1) {
2197 if (pos && boundary)
2199 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2200 rend = pm.pos2row(pos);
2202 rend = pm.pos2row(sl.pos());
2204 size_t rend = pm.pos2row(sl.pos());
2206 for (size_t rit = 0; rit != rend; ++rit)
2207 y += pm.rows()[rit].height();
2208 y += pm.rows()[rend].ascent();
2210 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2212 // Make relative position from the nested inset now bufferview absolute.
2213 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2216 // In the RTL case place the nested inset at the left of the cursor in
2217 // the outer paragraph
2218 bool boundary_1 = boundary && 1 == dit.depth();
2219 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2227 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2229 if (!paragraphVisible(dit))
2230 return Point(-1, -1);
2232 CursorSlice const & bot = dit.bottom();
2233 TextMetrics const & tm = textMetrics(bot.text());
2235 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2236 p.y_ += tm.parMetrics(bot.pit()).position();
2241 bool BufferView::paragraphVisible(DocIterator const & dit) const
2243 CursorSlice const & bot = dit.bottom();
2244 TextMetrics const & tm = textMetrics(bot.text());
2246 return tm.contains(bot.pit());
2250 void BufferView::draw(frontend::Painter & pain)
2252 if (height_ == 0 || width_ == 0)
2254 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2256 Text & text = buffer_.text();
2257 TextMetrics const & tm = d->text_metrics_[&text];
2258 int const y = tm.first().second->position();
2259 PainterInfo pi(this, pain);
2261 switch (d->update_strategy_) {
2263 case NoScreenUpdate:
2264 // If no screen painting is actually needed, only some the different
2265 // coordinates of insets and paragraphs needs to be updated.
2266 pi.full_repaint = true;
2267 pi.pain.setDrawingEnabled(false);
2271 case SingleParUpdate:
2272 pi.full_repaint = false;
2273 // In general, only the current row of the outermost paragraph
2274 // will be redrawn. Particular cases where selection spans
2275 // multiple paragraph are correctly detected in TextMetrics.
2279 case DecorationUpdate:
2280 // FIXME: We should also distinguish DecorationUpdate to avoid text
2281 // drawing if possible. This is not possible to do easily right now
2282 // because of the single backing pixmap.
2284 case FullScreenUpdate:
2285 // The whole screen, including insets, will be refreshed.
2286 pi.full_repaint = true;
2288 // Clear background.
2289 pain.fillRectangle(0, 0, width_, height_,
2290 pi.backgroundColor(&buffer_.inset()));
2295 // and possibly grey out below
2296 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2297 int const y2 = lastpm.second->position() + lastpm.second->descent();
2299 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2302 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2304 // The scrollbar needs an update.
2307 // Normalize anchor for next time
2308 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2309 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2310 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2311 ParagraphMetrics const & pm = tm.parMetrics(pit);
2312 if (pm.position() + pm.descent() > 0) {
2313 d->anchor_pit_ = pit;
2314 d->anchor_ypos_ = pm.position();
2318 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2319 << " anchor ypos = " << d->anchor_ypos_);
2323 void BufferView::message(docstring const & msg)
2326 d->gui_->message(msg);
2330 void BufferView::showDialog(string const & name)
2333 d->gui_->showDialog(name, string());
2337 void BufferView::showDialog(string const & name,
2338 string const & data, Inset * inset)
2341 d->gui_->showDialog(name, data, inset);
2345 void BufferView::updateDialog(string const & name, string const & data)
2348 d->gui_->updateDialog(name, data);
2352 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2358 // FIXME: Move this out of BufferView again
2359 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2361 if (!fname.isReadableFile()) {
2362 docstring const error = from_ascii(strerror(errno));
2363 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2364 docstring const text =
2365 bformat(_("Could not read the specified document\n"
2366 "%1$s\ndue to the error: %2$s"), file, error);
2367 Alert::error(_("Could not read file"), text);
2371 if (!fname.isReadableFile()) {
2372 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2373 docstring const text =
2374 bformat(_("%1$s\n is not readable."), file);
2375 Alert::error(_("Could not open file"), text);
2379 // FIXME UNICODE: We don't know the encoding of the file
2380 docstring file_content = fname.fileContents("UTF-8");
2381 if (file_content.empty()) {
2382 Alert::error(_("Reading not UTF-8 encoded file"),
2383 _("The file is not UTF-8 encoded.\n"
2384 "It will be read as local 8Bit-encoded.\n"
2385 "If this does not give the correct result\n"
2386 "then please change the encoding of the file\n"
2387 "to UTF-8 with a program other than LyX.\n"));
2388 file_content = fname.fileContents("local8bit");
2391 return normalize_c(file_content);
2395 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2397 docstring const tmpstr = contentsOfPlaintextFile(f);
2402 Cursor & cur = cursor();
2403 cap::replaceSelection(cur);
2404 buffer_.undo().recordUndo(cur);
2406 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2408 cur.innerText()->insertStringAsLines(cur, tmpstr);
2415 docstring const & BufferView::inlineCompletion() const
2417 return d->inlineCompletion_;
2421 size_t const & BufferView::inlineCompletionUniqueChars() const
2423 return d->inlineCompletionUniqueChars_;
2427 DocIterator const & BufferView::inlineCompletionPos() const
2429 return d->inlineCompletionPos_;
2433 bool samePar(DocIterator const & a, DocIterator const & b)
2435 if (a.empty() && b.empty())
2437 if (a.empty() || b.empty())
2439 return &a.innerParagraph() == &b.innerParagraph();
2443 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2444 docstring const & completion, size_t uniqueChars)
2446 uniqueChars = min(completion.size(), uniqueChars);
2447 bool changed = d->inlineCompletion_ != completion
2448 || d->inlineCompletionUniqueChars_ != uniqueChars;
2449 bool singlePar = true;
2450 d->inlineCompletion_ = completion;
2451 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2453 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2456 DocIterator const & old = d->inlineCompletionPos_;
2458 //lyxerr << "inlineCompletionPos changed" << std::endl;
2459 // old or pos are in another paragraph?
2460 if ((!samePar(cur, pos) && !pos.empty())
2461 || (!samePar(cur, old) && !old.empty())) {
2463 //lyxerr << "different paragraph" << std::endl;
2465 d->inlineCompletionPos_ = pos;
2470 if (singlePar && !(cur.disp_.update() & Update::Force))
2471 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2473 cur.updateFlags(cur.disp_.update() | Update::Force);