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 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
154 if (!findNextInset(tmpdit, codes, contents))
165 /// Looks for next inset with the given code
166 void findInset(DocIterator & dit, InsetCode code, bool same_content)
168 findInset(dit, vector<InsetCode>(1, code), same_content);
172 /// Moves cursor to the next inset with one of the given codes.
173 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
176 Cursor tmpcur = bv->cursor();
177 if (!findInset(tmpcur, codes, same_content)) {
178 bv->cursor().message(_("No more insets"));
182 tmpcur.clearSelection();
183 bv->setCursor(tmpcur);
188 /// Moves cursor to the next inset with given code.
189 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
191 gotoInset(bv, vector<InsetCode>(1, code), same_content);
195 /// A map from a Text to the associated text metrics
196 typedef map<Text const *, TextMetrics> TextMetricsCache;
198 enum ScreenUpdateStrategy {
208 /////////////////////////////////////////////////////////////////////
212 /////////////////////////////////////////////////////////////////////
214 struct BufferView::Private
216 Private(BufferView & bv): wh_(0), cursor_(bv),
217 anchor_pit_(0), anchor_ypos_(0),
218 inlineCompletionUniqueChars_(0),
219 last_inset_(0), gui_(0)
223 ScrollbarParameters scrollbarParameters_;
225 ScreenUpdateStrategy update_strategy_;
227 CoordCache coord_cache_;
229 /// Estimated average par height for scrollbar.
231 /// this is used to handle XSelection events in the right manner.
240 pit_type anchor_pit_;
244 vector<int> par_height_;
247 DocIterator inlineCompletionPos_;
249 docstring inlineCompletion_;
251 size_t inlineCompletionUniqueChars_;
253 /// keyboard mapping object.
256 /// last visited inset.
257 /** kept to send setMouseHover(false).
258 * Not owned, so don't delete.
262 mutable TextMetricsCache text_metrics_;
265 /** Not owned, so don't delete.
267 frontend::GuiBufferViewDelegate * gui_;
269 /// Cache for Find Next
270 FuncRequest search_request_cache_;
274 BufferView::BufferView(Buffer & buf)
275 : width_(0), height_(0), full_screen_(false), buffer_(buf), d(new Private(*this))
277 d->xsel_cache_.set = false;
278 d->intl_.initKeyMapper(lyxrc.use_kbmap);
280 d->cursor_.push(buffer_.inset());
281 d->cursor_.resetAnchor();
282 d->cursor_.setCurrentFont();
284 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
285 thePreviews().generateBufferPreviews(buffer_);
289 BufferView::~BufferView()
291 // current buffer is going to be switched-off, save cursor pos
292 // Ideally, the whole cursor stack should be saved, but session
293 // currently can only handle bottom (whole document) level pit and pos.
294 // That is to say, if a cursor is in a nested inset, it will be
295 // restore to the left of the top level inset.
296 LastFilePosSection::FilePos fp;
297 fp.pit = d->cursor_.bottom().pit();
298 fp.pos = d->cursor_.bottom().pos();
299 theSession().lastFilePos().save(buffer_.fileName(), fp);
305 int BufferView::rightMargin() const
307 // The additional test for the case the outliner is opened.
309 !lyxrc.full_screen_limit ||
310 width_ < lyxrc.full_screen_width + 20)
313 return (width_ - lyxrc.full_screen_width) / 2;
317 int BufferView::leftMargin() const
319 return rightMargin();
323 bool BufferView::isTopScreen() const
325 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
329 bool BufferView::isBottomScreen() const
331 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
335 Intl & BufferView::getIntl()
341 Intl const & BufferView::getIntl() const
347 CoordCache & BufferView::coordCache()
349 return d->coord_cache_;
353 CoordCache const & BufferView::coordCache() const
355 return d->coord_cache_;
359 Buffer & BufferView::buffer()
365 Buffer const & BufferView::buffer() const
371 bool BufferView::fitCursor()
373 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
374 frontend::FontMetrics const & fm =
375 theFontMetrics(d->cursor_.getFont().fontInfo());
376 int const asc = fm.maxAscent();
377 int const des = fm.maxDescent();
378 Point const p = getPos(d->cursor_, d->cursor_.boundary());
379 if (p.y_ - asc >= 0 && p.y_ + des < height_)
386 void BufferView::processUpdateFlags(Update::flags flags)
388 // last_inset_ points to the last visited inset. This pointer may become
389 // invalid because of keyboard editing. Since all such operations
390 // causes screen update(), I reset last_inset_ to avoid such a problem.
392 // This is close to a hot-path.
393 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
394 << "[fitcursor = " << (flags & Update::FitCursor)
395 << ", forceupdate = " << (flags & Update::Force)
396 << ", singlepar = " << (flags & Update::SinglePar)
397 << "] buffer: " << &buffer_);
399 buffer_.updateMacros();
401 // Now do the first drawing step if needed. This consists on updating
402 // the CoordCache in updateMetrics().
403 // The second drawing step is done in WorkArea::redraw() if needed.
405 // Case when no explicit update is requested.
407 // no need to redraw anything.
408 d->update_strategy_ = NoScreenUpdate;
412 if (flags == Update::Decoration) {
413 d->update_strategy_ = DecorationUpdate;
418 if (flags == Update::FitCursor
419 || flags == (Update::Decoration | Update::FitCursor)) {
420 // tell the frontend to update the screen if needed.
425 if (flags & Update::Decoration) {
426 d->update_strategy_ = DecorationUpdate;
430 // no screen update is needed.
431 d->update_strategy_ = NoScreenUpdate;
435 bool const full_metrics = flags & Update::Force || !singleParUpdate();
438 // We have to update the full screen metrics.
441 if (!(flags & Update::FitCursor)) {
442 // Nothing to do anymore. Trigger a redraw and return
447 // updateMetrics() does not update paragraph position
448 // This is done at draw() time. So we need a redraw!
452 // The cursor is off screen so ensure it is visible.
459 void BufferView::updateScrollbar()
461 if (height_ == 0 && width_ == 0)
464 // We prefer fixed size line scrolling.
465 d->scrollbarParameters_.single_step = defaultRowHeight();
466 // We prefer full screen page scrolling.
467 d->scrollbarParameters_.page_step = height_;
469 Text & t = buffer_.text();
470 TextMetrics & tm = d->text_metrics_[&t];
472 LYXERR(Debug::GUI, " Updating scrollbar: height: "
473 << t.paragraphs().size()
474 << " curr par: " << d->cursor_.bottom().pit()
475 << " default height " << defaultRowHeight());
477 size_t const parsize = t.paragraphs().size();
478 if (d->par_height_.size() != parsize) {
479 d->par_height_.clear();
480 // FIXME: We assume a default paragraph height of 2 rows. This
481 // should probably be pondered with the screen width.
482 d->par_height_.resize(parsize, defaultRowHeight() * 2);
485 // Look at paragraph heights on-screen
486 pair<pit_type, ParagraphMetrics const *> first = tm.first();
487 pair<pit_type, ParagraphMetrics const *> last = tm.last();
488 for (pit_type pit = first.first; pit <= last.first; ++pit) {
489 d->par_height_[pit] = tm.parMetrics(pit).height();
490 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
491 << d->par_height_[pit]);
494 int top_pos = first.second->position() - first.second->ascent();
495 int bottom_pos = last.second->position() + last.second->descent();
496 bool first_visible = first.first == 0 && top_pos >= 0;
497 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
498 if (first_visible && last_visible) {
499 d->scrollbarParameters_.min = 0;
500 d->scrollbarParameters_.max = 0;
504 d->scrollbarParameters_.min = top_pos;
505 for (size_t i = 0; i != size_t(first.first); ++i)
506 d->scrollbarParameters_.min -= d->par_height_[i];
507 d->scrollbarParameters_.max = bottom_pos;
508 for (size_t i = last.first + 1; i != parsize; ++i)
509 d->scrollbarParameters_.max += d->par_height_[i];
511 d->scrollbarParameters_.position = 0;
512 // The reference is the top position so we remove one page.
513 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
517 ScrollbarParameters const & BufferView::scrollbarParameters() const
519 return d->scrollbarParameters_;
523 docstring BufferView::toolTip(int x, int y) const
525 // Get inset under mouse, if there is one.
526 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
528 // No inset, no tooltip...
530 return covering_inset->toolTip(*this, x, y);
534 docstring BufferView::contextMenu(int x, int y) const
536 // Get inset under mouse, if there is one.
537 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
539 return covering_inset->contextMenu(*this, x, y);
541 return buffer_.inset().contextMenu(*this, x, y);
545 void BufferView::scrollDocView(int value)
547 int const offset = value - d->scrollbarParameters_.position;
548 // If the offset is less than 2 screen height, prefer to scroll instead.
549 if (abs(offset) <= 2 * height_) {
556 // cut off at the top
557 if (value <= d->scrollbarParameters_.min) {
558 DocIterator dit = doc_iterator_begin(buffer_.inset());
560 LYXERR(Debug::SCROLLING, "scroll to top");
564 // cut off at the bottom
565 if (value >= d->scrollbarParameters_.max) {
566 DocIterator dit = doc_iterator_end(buffer_.inset());
569 LYXERR(Debug::SCROLLING, "scroll to bottom");
573 // find paragraph at target position
574 int par_pos = d->scrollbarParameters_.min;
576 for (; i != int(d->par_height_.size()); ++i) {
577 par_pos += d->par_height_[i];
578 if (par_pos >= value)
582 if (par_pos < value) {
583 // It seems we didn't find the correct pit so stay on the safe side and
585 LYXERR0("scrolling position not found!");
586 scrollDocView(d->scrollbarParameters_.max);
590 DocIterator dit = doc_iterator_begin(buffer_.inset());
592 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
597 // FIXME: this method is not working well.
598 void BufferView::setCursorFromScrollbar()
600 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
602 int const height = 2 * defaultRowHeight();
603 int const first = height;
604 int const last = height_ - height;
605 Cursor & cur = d->cursor_;
607 switch (cursorStatus(cur)) {
609 // We reset the cursor because cursorStatus() does not
610 // work when the cursor is within mathed.
611 cur.reset(buffer_.inset());
612 tm.setCursorFromCoordinates(cur, 0, first);
613 cur.clearSelection();
616 // We reset the cursor because cursorStatus() does not
617 // work when the cursor is within mathed.
618 cur.reset(buffer_.inset());
619 tm.setCursorFromCoordinates(cur, 0, last);
620 cur.clearSelection();
623 int const y = getPos(cur, cur.boundary()).y_;
624 int const newy = min(last, max(y, first));
626 cur.reset(buffer_.inset());
627 tm.setCursorFromCoordinates(cur, 0, newy);
633 Change const BufferView::getCurrentChange() const
635 if (!d->cursor_.selection())
636 return Change(Change::UNCHANGED);
638 DocIterator dit = d->cursor_.selectionBegin();
639 return dit.paragraph().lookupChange(dit.pos());
643 // this could be used elsewhere as well?
644 // FIXME: This does not work within mathed!
645 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
647 Point const p = getPos(dit, dit.boundary());
650 if (p.y_ > workHeight())
656 void BufferView::saveBookmark(unsigned int idx)
658 // tenatively save bookmark, id and pos will be used to
659 // acturately locate a bookmark in a 'live' lyx session.
660 // pit and pos will be updated with bottom level pit/pos
662 theSession().bookmarks().save(
664 d->cursor_.bottom().pit(),
665 d->cursor_.bottom().pos(),
666 d->cursor_.paragraph().id(),
671 // emit message signal.
672 message(_("Save bookmark"));
676 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
677 int top_id, pos_type top_pos)
679 bool success = false;
682 d->cursor_.clearSelection();
684 // if a valid par_id is given, try it first
685 // This is the case for a 'live' bookmark when unique paragraph ID
686 // is used to track bookmarks.
688 dit = buffer_.getParFromID(top_id);
690 dit.pos() = min(dit.paragraph().size(), top_pos);
691 // Some slices of the iterator may not be
692 // reachable (e.g. closed collapsable inset)
693 // so the dociterator may need to be
694 // shortened. Otherwise, setCursor may crash
695 // lyx when the cursor can not be set to these
697 size_t const n = dit.depth();
698 for (size_t i = 0; i < n; ++i)
699 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
707 // if top_id == 0, or searching through top_id failed
708 // This is the case for a 'restored' bookmark when only bottom
709 // (document level) pit was saved. Because of this, bookmark
710 // restoration is inaccurate. If a bookmark was within an inset,
711 // it will be restored to the left of the outmost inset that contains
713 if (bottom_pit < int(buffer_.paragraphs().size())) {
714 dit = doc_iterator_begin(buffer_.inset());
716 dit.pit() = bottom_pit;
717 dit.pos() = min(bottom_pos, dit.paragraph().size());
722 // Note: only bottom (document) level pit is set.
724 // set the current font.
725 d->cursor_.setCurrentFont();
726 // To center the screen on this new position we need the
727 // paragraph position which is computed at draw() time.
728 // So we need a redraw!
738 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
740 if (lyxrc.rtl_support) {
741 if (d->cursor_.real_current_font.isRightToLeft()) {
742 if (d->intl_.keymap == Intl::PRIMARY)
743 d->intl_.keyMapSec();
745 if (d->intl_.keymap == Intl::SECONDARY)
746 d->intl_.keyMapPrim();
750 d->intl_.getTransManager().translateAndInsert(c, t, cur);
754 int BufferView::workWidth() const
760 void BufferView::showCursor()
762 showCursor(d->cursor_);
766 void BufferView::showCursor(DocIterator const & dit)
768 // We are not properly started yet, delay until resizing is
773 LYXERR(Debug::SCROLLING, "recentering!");
775 CursorSlice const & bot = dit.bottom();
776 TextMetrics & tm = d->text_metrics_[bot.text()];
778 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
779 int bot_pit = bot.pit();
780 if (bot_pit > max_pit) {
781 // FIXME: Why does this happen?
782 LYXERR0("bottom pit is greater that max pit: "
783 << bot_pit << " > " << max_pit);
787 if (bot_pit == tm.first().first - 1)
788 tm.newParMetricsUp();
789 else if (bot_pit == tm.last().first + 1)
790 tm.newParMetricsDown();
792 if (tm.contains(bot_pit)) {
793 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
794 LASSERT(!pm.rows().empty(), /**/);
795 // FIXME: smooth scrolling doesn't work in mathed.
796 CursorSlice const & cs = dit.innerTextSlice();
797 int offset = coordOffset(dit, dit.boundary()).y_;
798 int ypos = pm.position() + offset;
799 Dimension const & row_dim =
800 pm.getRow(cs.pos(), dit.boundary()).dimension();
802 if (ypos - row_dim.ascent() < 0)
803 scrolled = scrollUp(- ypos + row_dim.ascent());
804 else if (ypos + row_dim.descent() > height_)
805 scrolled = scrollDown(ypos - height_ + row_dim.descent());
806 // else, nothing to do, the cursor is already visible so we just return.
814 // fix inline completion position
815 if (d->inlineCompletionPos_.fixIfBroken())
816 d->inlineCompletionPos_ = DocIterator();
818 tm.redoParagraph(bot_pit);
819 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
820 int offset = coordOffset(dit, dit.boundary()).y_;
822 d->anchor_pit_ = bot_pit;
823 CursorSlice const & cs = dit.innerTextSlice();
824 Dimension const & row_dim =
825 pm.getRow(cs.pos(), dit.boundary()).dimension();
827 if (d->anchor_pit_ == 0)
828 d->anchor_ypos_ = offset + pm.ascent();
829 else if (d->anchor_pit_ == max_pit)
830 d->anchor_ypos_ = height_ - offset - row_dim.descent();
832 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
839 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
843 Cursor & cur = d->cursor_;
845 switch (cmd.action) {
848 flag.setEnabled(buffer_.undo().hasUndoStack());
851 flag.setEnabled(buffer_.undo().hasRedoStack());
853 case LFUN_FILE_INSERT:
854 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
855 case LFUN_FILE_INSERT_PLAINTEXT:
856 case LFUN_BOOKMARK_SAVE:
857 // FIXME: Actually, these LFUNS should be moved to Text
858 flag.setEnabled(cur.inTexted());
860 case LFUN_FONT_STATE:
861 case LFUN_LABEL_INSERT:
862 case LFUN_INFO_INSERT:
863 case LFUN_INSET_EDIT:
864 case LFUN_PARAGRAPH_GOTO:
866 case LFUN_REFERENCE_NEXT:
868 case LFUN_WORD_REPLACE:
871 case LFUN_MARK_TOGGLE:
872 case LFUN_SCREEN_RECENTER:
873 case LFUN_BIBTEX_DATABASE_ADD:
874 case LFUN_BIBTEX_DATABASE_DEL:
875 case LFUN_GRAPHICS_GROUPS_UNIFY:
876 case LFUN_NOTES_MUTATE:
877 case LFUN_ALL_INSETS_TOGGLE:
878 case LFUN_STATISTICS:
879 flag.setEnabled(true);
882 case LFUN_NEXT_INSET_TOGGLE:
883 case LFUN_NEXT_INSET_MODIFY: {
884 // this is the real function we want to invoke
885 FuncRequest tmpcmd = cmd;
886 tmpcmd.action = (cmd.action == LFUN_NEXT_INSET_TOGGLE)
887 ? LFUN_INSET_TOGGLE : LFUN_INSET_MODIFY;
888 // if there is an inset at cursor, see whether it
889 // handles the lfun, other start from scratch
890 Inset * inset = cur.nextInset();
891 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
892 flag = lyx::getStatus(tmpcmd);
896 case LFUN_LABEL_GOTO: {
897 flag.setEnabled(!cmd.argument().empty()
898 || getInsetByCode<InsetRef>(cur, REF_CODE));
902 case LFUN_CHANGES_TRACK:
903 flag.setEnabled(true);
904 flag.setOnOff(buffer_.params().trackChanges);
907 case LFUN_CHANGES_OUTPUT:
908 flag.setEnabled(true);
909 flag.setOnOff(buffer_.params().outputChanges);
912 case LFUN_CHANGES_MERGE:
913 case LFUN_CHANGE_NEXT:
914 case LFUN_ALL_CHANGES_ACCEPT:
915 case LFUN_ALL_CHANGES_REJECT:
916 // TODO: context-sensitive enabling of LFUNs
917 // In principle, these command should only be enabled if there
918 // is a change in the document. However, without proper
919 // optimizations, this will inevitably result in poor performance.
920 flag.setEnabled(true);
923 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
924 flag.setOnOff(buffer_.params().compressed);
929 case LFUN_SCREEN_DOWN:
931 case LFUN_SCREEN_UP_SELECT:
932 case LFUN_SCREEN_DOWN_SELECT:
933 flag.setEnabled(true);
936 case LFUN_LAYOUT_TABULAR:
937 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
941 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
944 case LFUN_LAYOUT_PARAGRAPH:
945 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
948 case LFUN_INSET_SETTINGS: {
949 InsetCode code = cur.inset().lyxCode();
950 if (cmd.getArg(0) == insetName(code)) {
951 flag.setEnabled(true);
955 InsetCode next_code = cur.nextInset()
956 ? cur.nextInset()->lyxCode() : NO_CODE;
957 //FIXME: remove these special cases:
967 enable = (cmd.argument().empty() ||
968 cmd.getArg(0) == insetName(next_code));
973 flag.setEnabled(enable);
977 case LFUN_DIALOG_SHOW_NEW_INSET:
978 flag.setEnabled(cur.inset().lyxCode() != ERT_CODE &&
979 cur.inset().lyxCode() != LISTINGS_CODE);
980 if (cur.inset().lyxCode() == CAPTION_CODE) {
982 if (cur.inset().getStatus(cur, cmd, flag))
987 case LFUN_BRANCH_ACTIVATE:
988 case LFUN_BRANCH_DEACTIVATE: {
990 docstring const branchName = cmd.argument();
991 if (!branchName.empty())
992 enable = buffer_.params().branchlist().find(branchName);
993 flag.setEnabled(enable);
998 flag.setEnabled(false);
1005 bool BufferView::dispatch(FuncRequest const & cmd)
1007 //lyxerr << [ cmd = " << cmd << "]" << endl;
1009 // Make sure that the cached BufferView is correct.
1010 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1011 << " arg[" << to_utf8(cmd.argument()) << ']'
1012 << " x[" << cmd.x << ']'
1013 << " y[" << cmd.y << ']'
1014 << " button[" << cmd.button() << ']');
1016 Cursor & cur = d->cursor_;
1018 switch (cmd.action) {
1021 cur.message(_("Undo"));
1022 cur.clearSelection();
1023 if (!cur.textUndo())
1024 cur.message(_("No further undo information"));
1026 processUpdateFlags(Update::Force | Update::FitCursor);
1030 cur.message(_("Redo"));
1031 cur.clearSelection();
1032 if (!cur.textRedo())
1033 cur.message(_("No further redo information"));
1035 processUpdateFlags(Update::Force | Update::FitCursor);
1038 case LFUN_FONT_STATE:
1039 cur.message(cur.currentState());
1042 case LFUN_BOOKMARK_SAVE:
1043 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1046 case LFUN_LABEL_GOTO: {
1047 docstring label = cmd.argument();
1048 if (label.empty()) {
1050 getInsetByCode<InsetRef>(d->cursor_,
1053 label = inset->getParam("reference");
1054 // persistent=false: use temp_bookmark
1064 case LFUN_INSET_EDIT: {
1065 FuncRequest fr(cmd);
1066 // if there is an inset at cursor, see whether it
1068 Inset * inset = cur.nextInset();
1070 inset->dispatch(cur, fr);
1071 // if it did not work, try the underlying inset.
1072 if (!inset || !cur.result().dispatched())
1075 if (!cur.result().dispatched())
1076 // It did not work too; no action needed.
1080 case LFUN_PARAGRAPH_GOTO: {
1081 int const id = convert<int>(cmd.getArg(0));
1082 int const pos = convert<int>(cmd.getArg(1));
1084 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1085 b = theBufferList().next(b)) {
1087 DocIterator dit = b->getParFromID(id);
1089 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1093 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1094 << " found in buffer `"
1095 << b->absFileName() << "'.");
1097 if (b == &buffer_) {
1101 processUpdateFlags(Update::Force | Update::FitCursor);
1103 // Switch to other buffer view and resend cmd
1104 theLyXFunc().dispatch(FuncRequest(
1105 LFUN_BUFFER_SWITCH, b->absFileName()));
1106 theLyXFunc().dispatch(cmd);
1113 case LFUN_NOTE_NEXT:
1114 gotoInset(this, NOTE_CODE, false);
1117 case LFUN_REFERENCE_NEXT: {
1118 vector<InsetCode> tmp;
1119 tmp.push_back(LABEL_CODE);
1120 tmp.push_back(REF_CODE);
1121 gotoInset(this, tmp, true);
1125 case LFUN_CHANGES_TRACK:
1126 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1129 case LFUN_CHANGES_OUTPUT:
1130 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1131 if (buffer_.params().outputChanges) {
1132 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1133 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1134 LaTeXFeatures::isAvailable("xcolor");
1136 if (!dvipost && !xcolorsoul) {
1137 Alert::warning(_("Changes not shown in LaTeX output"),
1138 _("Changes will not be highlighted in LaTeX output, "
1139 "because neither dvipost nor xcolor/soul are installed.\n"
1140 "Please install these packages or redefine "
1141 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1142 } else if (!xcolorsoul) {
1143 Alert::warning(_("Changes not shown in LaTeX output"),
1144 _("Changes will not be highlighted in LaTeX output "
1145 "when using pdflatex, because xcolor and soul are not installed.\n"
1146 "Please install both packages or redefine "
1147 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1152 case LFUN_CHANGE_NEXT:
1153 findNextChange(this);
1156 case LFUN_CHANGES_MERGE:
1157 if (findNextChange(this))
1158 showDialog("changes");
1161 case LFUN_ALL_CHANGES_ACCEPT:
1162 // select complete document
1163 d->cursor_.reset(buffer_.inset());
1164 d->cursor_.selHandle(true);
1165 buffer_.text().cursorBottom(d->cursor_);
1166 // accept everything in a single step to support atomic undo
1167 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1168 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1169 processUpdateFlags(Update::Force | Update::FitCursor);
1172 case LFUN_ALL_CHANGES_REJECT:
1173 // select complete document
1174 d->cursor_.reset(buffer_.inset());
1175 d->cursor_.selHandle(true);
1176 buffer_.text().cursorBottom(d->cursor_);
1177 // reject everything in a single step to support atomic undo
1178 // Note: reject does not work recursively; the user may have to repeat the operation
1179 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1180 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1181 processUpdateFlags(Update::Force | Update::FitCursor);
1184 case LFUN_WORD_FIND: {
1185 FuncRequest req = cmd;
1186 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1187 req = d->search_request_cache_;
1188 if (find(this, req))
1191 message(_("String not found!"));
1192 d->search_request_cache_ = req;
1196 case LFUN_WORD_REPLACE: {
1197 bool has_deleted = false;
1198 if (cur.selection()) {
1199 DocIterator beg = cur.selectionBegin();
1200 DocIterator end = cur.selectionEnd();
1201 if (beg.pit() == end.pit()) {
1202 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1203 if (cur.paragraph().isDeleted(p))
1208 replace(this, cmd, has_deleted);
1213 cur.clearSelection();
1215 cur.message(from_utf8(N_("Mark off")));
1219 cur.clearSelection();
1222 cur.message(from_utf8(N_("Mark on")));
1225 case LFUN_MARK_TOGGLE:
1226 cur.clearSelection();
1229 cur.message(from_utf8(N_("Mark removed")));
1232 cur.message(from_utf8(N_("Mark set")));
1237 case LFUN_SCREEN_RECENTER:
1241 case LFUN_BIBTEX_DATABASE_ADD: {
1242 Cursor tmpcur = d->cursor_;
1243 findInset(tmpcur, BIBTEX_CODE, false);
1244 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1247 if (inset->addDatabase(cmd.argument()))
1248 buffer_.updateBibfilesCache();
1253 case LFUN_BIBTEX_DATABASE_DEL: {
1254 Cursor tmpcur = d->cursor_;
1255 findInset(tmpcur, BIBTEX_CODE, false);
1256 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1259 if (inset->delDatabase(cmd.argument()))
1260 buffer_.updateBibfilesCache();
1265 case LFUN_STATISTICS: {
1266 DocIterator from, to;
1267 if (cur.selection()) {
1268 from = cur.selectionBegin();
1269 to = cur.selectionEnd();
1271 from = doc_iterator_begin(buffer_.inset());
1272 to = doc_iterator_end(buffer_.inset());
1274 int const words = countWords(from, to);
1275 int const chars = countChars(from, to, false);
1276 int const chars_blanks = countChars(from, to, true);
1278 if (cur.selection())
1279 message = _("Statistics for the selection:");
1281 message = _("Statistics for the document:");
1284 message += bformat(_("%1$d words"), words);
1286 message += _("One word");
1288 if (chars_blanks != 1)
1289 message += bformat(_("%1$d characters (including blanks)"),
1292 message += _("One character (including blanks)");
1295 message += bformat(_("%1$d characters (excluding blanks)"),
1298 message += _("One character (excluding blanks)");
1300 Alert::information(_("Statistics"), message);
1304 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1305 // turn compression on/off
1306 buffer_.params().compressed = !buffer_.params().compressed;
1309 case LFUN_NEXT_INSET_TOGGLE: {
1310 // create the the real function we want to invoke
1311 FuncRequest tmpcmd = cmd;
1312 tmpcmd.action = LFUN_INSET_TOGGLE;
1313 // if there is an inset at cursor, see whether it
1315 Inset * inset = cur.nextInset();
1317 if (inset->isActive()) {
1318 Cursor tmpcur = cur;
1319 tmpcur.pushBackward(*inset);
1320 inset->dispatch(tmpcur, tmpcmd);
1321 if (tmpcur.result().dispatched())
1324 inset->dispatch(cur, tmpcmd);
1326 // if it did not work, try the underlying inset.
1327 if (!inset || !cur.result().dispatched())
1328 cur.dispatch(tmpcmd);
1330 if (!cur.result().dispatched())
1331 // It did not work too; no action needed.
1333 cur.clearSelection();
1334 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1338 case LFUN_NEXT_INSET_MODIFY: {
1339 // create the the real function we want to invoke
1340 FuncRequest tmpcmd = cmd;
1341 tmpcmd.action = LFUN_INSET_MODIFY;
1342 // if there is an inset at cursor, see whether it
1344 Inset * inset = cur.nextInset();
1346 inset->dispatch(cur, tmpcmd);
1347 // if it did not work, try the underlying inset.
1348 if (!inset || !cur.result().dispatched())
1349 cur.dispatch(tmpcmd);
1351 if (!cur.result().dispatched())
1352 // It did not work too; no action needed.
1354 cur.clearSelection();
1355 processUpdateFlags(Update::Force | Update::FitCursor);
1359 case LFUN_SCREEN_UP:
1360 case LFUN_SCREEN_DOWN: {
1361 Point p = getPos(cur, cur.boundary());
1362 if (p.y_ < 0 || p.y_ > height_) {
1363 // The cursor is off-screen so recenter before proceeding.
1365 p = getPos(cur, cur.boundary());
1367 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1368 ? - height_ : height_);
1369 if (cmd.action == LFUN_SCREEN_UP && scrolled > - height_)
1371 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1372 p = Point(width_, height_);
1373 cur.reset(buffer_.inset());
1376 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1377 //FIXME: what to do with cur.x_target()?
1386 case LFUN_SCREEN_UP_SELECT: {
1387 cur.selHandle(true);
1388 if (isTopScreen()) {
1389 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1393 int y = getPos(cur, cur.boundary()).y_;
1394 int const ymin = y - height_ + defaultRowHeight();
1395 while (y > ymin && cur.up())
1396 y = getPos(cur, cur.boundary()).y_;
1399 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1403 case LFUN_SCREEN_DOWN_SELECT: {
1404 cur.selHandle(true);
1405 if (isBottomScreen()) {
1406 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1410 int y = getPos(cur, cur.boundary()).y_;
1411 int const ymax = y + height_ - defaultRowHeight();
1412 while (y < ymax && cur.down())
1413 y = getPos(cur, cur.boundary()).y_;
1416 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1420 case LFUN_BRANCH_ACTIVATE:
1421 case LFUN_BRANCH_DEACTIVATE:
1422 buffer_.dispatch(cmd);
1423 processUpdateFlags(Update::Force);
1426 // These two could be rewriten using some command like forall <insetname> <command>
1427 // once the insets refactoring is done.
1428 case LFUN_GRAPHICS_GROUPS_UNIFY: {
1429 if (cmd.argument().empty())
1431 //view()->cursor().recordUndoFullDocument(); let inset-apply do that job
1432 graphics::unifyGraphicsGroups(cur.buffer(), to_utf8(cmd.argument()));
1433 processUpdateFlags(Update::Force | Update::FitCursor);
1437 case LFUN_NOTES_MUTATE: {
1438 if (cmd.argument().empty())
1440 cur.recordUndoFullDocument();
1442 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1443 processUpdateFlags(Update::Force);
1448 case LFUN_ALL_INSETS_TOGGLE: {
1450 string const name = split(to_utf8(cmd.argument()), action, ' ');
1451 InsetCode const inset_code = insetCode(name);
1453 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1455 Inset & inset = cur.buffer().inset();
1456 InsetIterator it = inset_iterator_begin(inset);
1457 InsetIterator const end = inset_iterator_end(inset);
1458 for (; it != end; ++it) {
1459 if (!it->asInsetMath()
1460 && (inset_code == NO_CODE
1461 || inset_code == it->lyxCode())) {
1462 Cursor tmpcur = cur;
1463 tmpcur.pushBackward(*it);
1465 it->getStatus(tmpcur, fr, flag);
1467 it->dispatch(tmpcur, fr);
1470 processUpdateFlags(Update::Force | Update::FitCursor);
1482 docstring const BufferView::requestSelection()
1484 Cursor & cur = d->cursor_;
1486 if (!cur.selection()) {
1487 d->xsel_cache_.set = false;
1491 if (!d->xsel_cache_.set ||
1492 cur.top() != d->xsel_cache_.cursor ||
1493 cur.anchor_.top() != d->xsel_cache_.anchor)
1495 d->xsel_cache_.cursor = cur.top();
1496 d->xsel_cache_.anchor = cur.anchor_.top();
1497 d->xsel_cache_.set = cur.selection();
1498 return cur.selectionAsString(false);
1504 void BufferView::clearSelection()
1506 d->cursor_.clearSelection();
1507 // Clear the selection buffer. Otherwise a subsequent
1508 // middle-mouse-button paste would use the selection buffer,
1509 // not the more current external selection.
1510 cap::clearSelection();
1511 d->xsel_cache_.set = false;
1512 // The buffer did not really change, but this causes the
1513 // redraw we need because we cleared the selection above.
1518 void BufferView::resize(int width, int height)
1520 // Update from work area
1524 // Clear the paragraph height cache.
1525 d->par_height_.clear();
1526 // Redo the metrics.
1531 Inset const * BufferView::getCoveringInset(Text const & text,
1534 TextMetrics & tm = d->text_metrics_[&text];
1535 Inset * inset = tm.checkInsetHit(x, y);
1539 if (!inset->descendable())
1540 // No need to go further down if the inset is not
1544 size_t cell_number = inset->nargs();
1545 // Check all the inner cell.
1546 for (size_t i = 0; i != cell_number; ++i) {
1547 Text const * inner_text = inset->getText(i);
1550 Inset const * inset_deeper =
1551 getCoveringInset(*inner_text, x, y);
1553 return inset_deeper;
1561 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1563 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1565 // This is only called for mouse related events including
1566 // LFUN_FILE_OPEN generated by drag-and-drop.
1567 FuncRequest cmd = cmd0;
1569 Cursor old = cursor();
1571 cur.push(buffer_.inset());
1572 cur.selection() = d->cursor_.selection();
1574 // Either the inset under the cursor or the
1575 // surrounding Text will handle this event.
1577 // make sure we stay within the screen...
1578 cmd.y = min(max(cmd.y, -1), height_);
1580 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1582 // Get inset under mouse, if there is one.
1583 Inset const * covering_inset =
1584 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1585 if (covering_inset == d->last_inset_)
1586 // Same inset, no need to do anything...
1589 bool need_redraw = false;
1590 // const_cast because of setMouseHover().
1591 Inset * inset = const_cast<Inset *>(covering_inset);
1593 // Remove the hint on the last hovered inset (if any).
1594 need_redraw |= d->last_inset_->setMouseHover(false);
1596 // Highlighted the newly hovered inset (if any).
1597 need_redraw |= inset->setMouseHover(true);
1598 d->last_inset_ = inset;
1602 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1603 << cmd.x << ", " << cmd.y << ")");
1605 d->update_strategy_ = DecorationUpdate;
1607 // This event (moving without mouse click) is not passed further.
1608 // This should be changed if it is further utilized.
1613 // Build temporary cursor.
1614 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1616 // Put anchor at the same position.
1619 // Try to dispatch to an non-editable inset near this position
1620 // via the temp cursor. If the inset wishes to change the real
1621 // cursor it has to do so explicitly by using
1622 // cur.bv().cursor() = cur; (or similar)
1624 inset->dispatch(cur, cmd);
1626 // Now dispatch to the temporary cursor. If the real cursor should
1627 // be modified, the inset's dispatch has to do so explicitly.
1628 if (!inset || !cur.result().dispatched())
1631 // Notify left insets
1634 bool badcursor = notifyCursorLeaves(old, cur);
1636 cursor().fixIfBroken();
1639 // Do we have a selection?
1640 theSelection().haveSelection(cursor().selection());
1642 // If the command has been dispatched,
1643 if (cur.result().dispatched() || cur.result().update())
1644 processUpdateFlags(cur.result().update());
1648 void BufferView::lfunScroll(FuncRequest const & cmd)
1650 string const scroll_type = cmd.getArg(0);
1651 int const scroll_step =
1652 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1653 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1654 if (scroll_step == 0)
1656 string const scroll_quantity = cmd.getArg(1);
1657 if (scroll_quantity == "up")
1658 scrollUp(scroll_step);
1659 else if (scroll_quantity == "down")
1660 scrollDown(scroll_step);
1662 int const scroll_value = convert<int>(scroll_quantity);
1664 scroll(scroll_step * scroll_value);
1671 int BufferView::scroll(int y)
1674 return scrollDown(y);
1676 return scrollUp(-y);
1681 int BufferView::scrollDown(int offset)
1683 Text * text = &buffer_.text();
1684 TextMetrics & tm = d->text_metrics_[text];
1685 int ymax = height_ + offset;
1687 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1688 int bottom_pos = last.second->position() + last.second->descent();
1689 if (last.first + 1 == int(text->paragraphs().size())) {
1690 if (bottom_pos <= height_)
1692 offset = min(offset, bottom_pos - height_);
1695 if (bottom_pos > ymax)
1697 tm.newParMetricsDown();
1699 d->anchor_ypos_ -= offset;
1704 int BufferView::scrollUp(int offset)
1706 Text * text = &buffer_.text();
1707 TextMetrics & tm = d->text_metrics_[text];
1708 int ymin = - offset;
1710 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1711 int top_pos = first.second->position() - first.second->ascent();
1712 if (first.first == 0) {
1715 offset = min(offset, - top_pos);
1720 tm.newParMetricsUp();
1722 d->anchor_ypos_ += offset;
1727 void BufferView::setCursorFromRow(int row)
1732 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1734 d->cursor_.reset(buffer_.inset());
1736 buffer_.text().setCursor(d->cursor_, 0, 0);
1738 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1742 void BufferView::gotoLabel(docstring const & label)
1744 Toc & toc = buffer().tocBackend().toc("label");
1745 TocIterator toc_it = toc.begin();
1746 TocIterator end = toc.end();
1747 for (; toc_it != end; ++toc_it) {
1748 if (label == toc_it->str())
1749 dispatch(toc_it->action());
1751 //FIXME: We could do a bit more searching thanks to this:
1752 //InsetLabel const * inset = buffer_.insetLabel(label);
1756 TextMetrics const & BufferView::textMetrics(Text const * t) const
1758 return const_cast<BufferView *>(this)->textMetrics(t);
1762 TextMetrics & BufferView::textMetrics(Text const * t)
1764 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1765 if (tmc_it == d->text_metrics_.end()) {
1766 tmc_it = d->text_metrics_.insert(
1767 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1769 return tmc_it->second;
1773 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1776 return textMetrics(t).parMetrics(pit);
1780 int BufferView::workHeight() const
1786 void BufferView::setCursor(DocIterator const & dit)
1788 size_t const n = dit.depth();
1789 for (size_t i = 0; i < n; ++i)
1790 dit[i].inset().edit(d->cursor_, true);
1792 d->cursor_.setCursor(dit);
1793 d->cursor_.selection() = false;
1797 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1799 // Would be wrong to delete anything if we have a selection.
1800 if (cur.selection())
1803 bool need_anchor_change = false;
1804 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1805 need_anchor_change);
1807 if (need_anchor_change)
1815 updateLabels(buffer_);
1823 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1825 LASSERT(&cur.bv() == this, /**/);
1828 // this event will clear selection so we save selection for
1829 // persistent selection
1830 cap::saveSelection(cursor());
1832 // Has the cursor just left the inset?
1833 bool badcursor = false;
1834 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1836 d->cursor_.fixIfBroken();
1837 badcursor = notifyCursorLeaves(d->cursor_, cur);
1842 // FIXME: shift-mouse selection doesn't work well across insets.
1843 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1845 // do the dEPM magic if needed
1846 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1847 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1848 // the leftinset bool would not be necessary (badcursor instead).
1849 bool update = leftinset;
1850 if (!do_selection && !badcursor && d->cursor_.inTexted())
1851 update |= checkDepm(cur, d->cursor_);
1853 d->cursor_.setCursor(cur);
1854 d->cursor_.boundary(cur.boundary());
1856 d->cursor_.setSelection();
1858 d->cursor_.clearSelection();
1860 d->cursor_.finishUndo();
1861 d->cursor_.setCurrentFont();
1866 void BufferView::putSelectionAt(DocIterator const & cur,
1867 int length, bool backwards)
1869 d->cursor_.clearSelection();
1875 d->cursor_.pos() += length;
1876 d->cursor_.setSelection(d->cursor_, -length);
1878 d->cursor_.setSelection(d->cursor_, length);
1880 // Ensure a redraw happens in any case because the new selection could
1881 // possibly be on the same screen as the previous selection.
1882 processUpdateFlags(Update::Force | Update::FitCursor);
1886 Cursor & BufferView::cursor()
1892 Cursor const & BufferView::cursor() const
1898 pit_type BufferView::anchor_ref() const
1900 return d->anchor_pit_;
1904 bool BufferView::singleParUpdate()
1906 Text & buftext = buffer_.text();
1907 pit_type const bottom_pit = d->cursor_.bottom().pit();
1908 TextMetrics & tm = textMetrics(&buftext);
1909 int old_height = tm.parMetrics(bottom_pit).height();
1911 // make sure inline completion pointer is ok
1912 if (d->inlineCompletionPos_.fixIfBroken())
1913 d->inlineCompletionPos_ = DocIterator();
1915 // In Single Paragraph mode, rebreak only
1916 // the (main text, not inset!) paragraph containing the cursor.
1917 // (if this paragraph contains insets etc., rebreaking will
1918 // recursively descend)
1919 tm.redoParagraph(bottom_pit);
1920 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1921 if (pm.height() != old_height)
1922 // Paragraph height has changed so we cannot proceed to
1923 // the singlePar optimisation.
1926 d->update_strategy_ = SingleParUpdate;
1928 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1929 << " y2: " << pm.position() + pm.descent()
1930 << " pit: " << bottom_pit
1931 << " singlepar: 1");
1936 void BufferView::updateMetrics()
1938 if (height_ == 0 || width_ == 0)
1941 Text & buftext = buffer_.text();
1942 pit_type const npit = int(buftext.paragraphs().size());
1944 // Clear out the position cache in case of full screen redraw,
1945 d->coord_cache_.clear();
1947 // Clear out paragraph metrics to avoid having invalid metrics
1948 // in the cache from paragraphs not relayouted below
1949 // The complete text metrics will be redone.
1950 d->text_metrics_.clear();
1952 TextMetrics & tm = textMetrics(&buftext);
1954 // make sure inline completion pointer is ok
1955 if (d->inlineCompletionPos_.fixIfBroken())
1956 d->inlineCompletionPos_ = DocIterator();
1958 if (d->anchor_pit_ >= npit)
1959 // The anchor pit must have been deleted...
1960 d->anchor_pit_ = npit - 1;
1962 // Rebreak anchor paragraph.
1963 tm.redoParagraph(d->anchor_pit_);
1964 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1967 if (d->anchor_pit_ == 0) {
1968 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
1970 // Complete buffer visible? Then it's easy.
1971 if (scrollRange == 0)
1972 d->anchor_ypos_ = anchor_pm.ascent();
1974 // FIXME: Some clever handling needed to show
1975 // the _first_ paragraph up to the top if the cursor is
1976 // in the first line.
1978 anchor_pm.setPosition(d->anchor_ypos_);
1980 LYXERR(Debug::PAINTING, "metrics: "
1981 << " anchor pit = " << d->anchor_pit_
1982 << " anchor ypos = " << d->anchor_ypos_);
1984 // Redo paragraphs above anchor if necessary.
1985 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1986 // We are now just above the anchor paragraph.
1987 pit_type pit1 = d->anchor_pit_ - 1;
1988 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1989 tm.redoParagraph(pit1);
1990 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1992 // Save the paragraph position in the cache.
1997 // Redo paragraphs below the anchor if necessary.
1998 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1999 // We are now just below the anchor paragraph.
2000 pit_type pit2 = d->anchor_pit_ + 1;
2001 for (; pit2 < npit && y2 <= height_; ++pit2) {
2002 tm.redoParagraph(pit2);
2003 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2005 // Save the paragraph position in the cache.
2010 LYXERR(Debug::PAINTING, "Metrics: "
2011 << " anchor pit = " << d->anchor_pit_
2012 << " anchor ypos = " << d->anchor_ypos_
2015 << " pit1 = " << pit1
2016 << " pit2 = " << pit2);
2018 d->update_strategy_ = FullScreenUpdate;
2020 if (lyxerr.debugging(Debug::WORKAREA)) {
2021 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2022 d->coord_cache_.dump();
2027 void BufferView::insertLyXFile(FileName const & fname)
2029 LASSERT(d->cursor_.inTexted(), /**/);
2031 // Get absolute path of file and add ".lyx"
2032 // to the filename if necessary
2033 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2035 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2036 // emit message signal.
2037 message(bformat(_("Inserting document %1$s..."), disp_fn));
2040 Buffer buf("", false);
2041 if (buf.loadLyXFile(filename)) {
2042 ErrorList & el = buffer_.errorList("Parse");
2043 // Copy the inserted document error list into the current buffer one.
2044 el = buf.errorList("Parse");
2045 buffer_.undo().recordUndo(d->cursor_);
2046 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2047 buf.params().documentClassPtr(), el);
2048 res = _("Document %1$s inserted.");
2050 res = _("Could not insert document %1$s");
2055 // emit message signal.
2056 message(bformat(res, disp_fn));
2057 buffer_.errors("Parse");
2061 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2067 // Addup contribution of nested insets, from inside to outside,
2068 // keeping the outer paragraph for a special handling below
2069 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2070 CursorSlice const & sl = dit[i];
2074 // get relative position inside sl.inset()
2075 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2077 // Make relative position inside of the edited inset relative to sl.inset()
2081 // In case of an RTL inset, the edited inset will be positioned to the left
2084 bool boundary_i = boundary && i + 1 == dit.depth();
2085 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2090 // remember width for the case that sl.inset() is positioned in an RTL inset
2091 if (i && dit[i - 1].text()) {
2092 // If this Inset is inside a Text Inset, retrieve the Dimension
2093 // from the containing text instead of using Inset::dimension() which
2094 // might not be implemented.
2095 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2096 // elimination of Inset::dim_ cache. This coordOffset() method needs
2097 // to be rewritten in light of the new design.
2098 Dimension const & dim = parMetrics(dit[i - 1].text(),
2099 dit[i - 1].pit()).insetDimension(&sl.inset());
2102 Dimension const dim = sl.inset().dimension(*this);
2106 //lyxerr << "Cursor::getPos, i: "
2107 // << i << " x: " << xx << " y: " << y << endl;
2110 // Add contribution of initial rows of outermost paragraph
2111 CursorSlice const & sl = dit[0];
2112 TextMetrics const & tm = textMetrics(sl.text());
2113 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2114 LASSERT(!pm.rows().empty(), /**/);
2115 y -= pm.rows()[0].ascent();
2117 // FIXME: document this mess
2119 if (sl.pos() > 0 && dit.depth() == 1) {
2121 if (pos && boundary)
2123 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2124 rend = pm.pos2row(pos);
2126 rend = pm.pos2row(sl.pos());
2128 size_t rend = pm.pos2row(sl.pos());
2130 for (size_t rit = 0; rit != rend; ++rit)
2131 y += pm.rows()[rit].height();
2132 y += pm.rows()[rend].ascent();
2134 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2136 // Make relative position from the nested inset now bufferview absolute.
2137 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2140 // In the RTL case place the nested inset at the left of the cursor in
2141 // the outer paragraph
2142 bool boundary_1 = boundary && 1 == dit.depth();
2143 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2151 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2153 CursorSlice const & bot = dit.bottom();
2154 TextMetrics const & tm = textMetrics(bot.text());
2155 if (!tm.contains(bot.pit()))
2156 return Point(-1, -1);
2158 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2159 p.y_ += tm.parMetrics(bot.pit()).position();
2164 void BufferView::draw(frontend::Painter & pain)
2166 if (height_ == 0 || width_ == 0)
2168 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2169 Text & text = buffer_.text();
2170 TextMetrics const & tm = d->text_metrics_[&text];
2171 int const y = tm.first().second->position();
2172 PainterInfo pi(this, pain);
2174 switch (d->update_strategy_) {
2176 case NoScreenUpdate:
2177 // If no screen painting is actually needed, only some the different
2178 // coordinates of insets and paragraphs needs to be updated.
2179 pi.full_repaint = true;
2180 pi.pain.setDrawingEnabled(false);
2184 case SingleParUpdate:
2185 pi.full_repaint = false;
2186 // In general, only the current row of the outermost paragraph
2187 // will be redrawn. Particular cases where selection spans
2188 // multiple paragraph are correctly detected in TextMetrics.
2192 case DecorationUpdate:
2193 // FIXME: We should also distinguish DecorationUpdate to avoid text
2194 // drawing if possible. This is not possible to do easily right now
2195 // because of the single backing pixmap.
2197 case FullScreenUpdate:
2198 // The whole screen, including insets, will be refreshed.
2199 pi.full_repaint = true;
2201 // Clear background.
2202 pain.fillRectangle(0, 0, width_, height_,
2203 buffer_.inset().backgroundColor());
2208 // and possibly grey out below
2209 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2210 int const y2 = lastpm.second->position() + lastpm.second->descent();
2212 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2215 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2217 // The scrollbar needs an update.
2220 // Normalize anchor for next time
2221 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2222 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2223 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2224 ParagraphMetrics const & pm = tm.parMetrics(pit);
2225 if (pm.position() + pm.descent() > 0) {
2226 d->anchor_pit_ = pit;
2227 d->anchor_ypos_ = pm.position();
2231 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2232 << " anchor ypos = " << d->anchor_ypos_);
2236 void BufferView::message(docstring const & msg)
2239 d->gui_->message(msg);
2243 void BufferView::showDialog(string const & name)
2246 d->gui_->showDialog(name, string());
2250 void BufferView::showDialog(string const & name,
2251 string const & data, Inset * inset)
2254 d->gui_->showDialog(name, data, inset);
2258 void BufferView::updateDialog(string const & name, string const & data)
2261 d->gui_->updateDialog(name, data);
2265 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2271 // FIXME: Move this out of BufferView again
2272 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2274 if (!fname.isReadableFile()) {
2275 docstring const error = from_ascii(strerror(errno));
2276 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2277 docstring const text =
2278 bformat(_("Could not read the specified document\n"
2279 "%1$s\ndue to the error: %2$s"), file, error);
2280 Alert::error(_("Could not read file"), text);
2284 if (!fname.isReadableFile()) {
2285 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2286 docstring const text =
2287 bformat(_("%1$s\n is not readable."), file);
2288 Alert::error(_("Could not open file"), text);
2292 // FIXME UNICODE: We don't know the encoding of the file
2293 docstring file_content = fname.fileContents("UTF-8");
2294 if (file_content.empty()) {
2295 Alert::error(_("Reading not UTF-8 encoded file"),
2296 _("The file is not UTF-8 encoded.\n"
2297 "It will be read as local 8Bit-encoded.\n"
2298 "If this does not give the correct result\n"
2299 "then please change the encoding of the file\n"
2300 "to UTF-8 with a program other than LyX.\n"));
2301 file_content = fname.fileContents("local8bit");
2304 return normalize_c(file_content);
2308 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2310 docstring const tmpstr = contentsOfPlaintextFile(f);
2315 Cursor & cur = cursor();
2316 cap::replaceSelection(cur);
2317 buffer_.undo().recordUndo(cur);
2319 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2321 cur.innerText()->insertStringAsLines(cur, tmpstr);
2328 docstring const & BufferView::inlineCompletion() const
2330 return d->inlineCompletion_;
2334 size_t const & BufferView::inlineCompletionUniqueChars() const
2336 return d->inlineCompletionUniqueChars_;
2340 DocIterator const & BufferView::inlineCompletionPos() const
2342 return d->inlineCompletionPos_;
2346 bool samePar(DocIterator const & a, DocIterator const & b)
2348 if (a.empty() && b.empty())
2350 if (a.empty() || b.empty())
2352 return &a.innerParagraph() == &b.innerParagraph();
2356 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2357 docstring const & completion, size_t uniqueChars)
2359 uniqueChars = min(completion.size(), uniqueChars);
2360 bool changed = d->inlineCompletion_ != completion
2361 || d->inlineCompletionUniqueChars_ != uniqueChars;
2362 bool singlePar = true;
2363 d->inlineCompletion_ = completion;
2364 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2366 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2369 DocIterator const & old = d->inlineCompletionPos_;
2371 //lyxerr << "inlineCompletionPos changed" << std::endl;
2372 // old or pos are in another paragraph?
2373 if ((!samePar(cur, pos) && !pos.empty())
2374 || (!samePar(cur, old) && !old.empty())) {
2376 //lyxerr << "different paragraph" << std::endl;
2378 d->inlineCompletionPos_ = pos;
2383 if (singlePar && !(cur.disp_.update() & Update::Force))
2384 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2386 cur.updateFlags(cur.disp_.update() | Update::Force);