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"
63 #include "frontends/alert.h"
64 #include "frontends/Application.h"
65 #include "frontends/Delegates.h"
66 #include "frontends/FontMetrics.h"
67 #include "frontends/Painter.h"
68 #include "frontends/Selection.h"
70 #include "graphics/Previews.h"
72 #include "support/convert.h"
73 #include "support/debug.h"
74 #include "support/ExceptionMessage.h"
75 #include "support/filetools.h"
76 #include "support/gettext.h"
77 #include "support/lstrings.h"
78 #include "support/Package.h"
79 #include "support/types.h"
88 using namespace lyx::support;
92 namespace Alert = frontend::Alert;
96 /// Return an inset of this class if it exists at the current cursor position
98 T * getInsetByCode(Cursor const & cur, InsetCode code)
100 DocIterator it = cur;
101 Inset * inset = it.nextInset();
102 if (inset && inset->lyxCode() == code)
103 return static_cast<T*>(inset);
108 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
111 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
112 docstring const & contents)
114 DocIterator tmpdit = dit;
117 Inset const * inset = tmpdit.nextInset();
119 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
120 && (contents.empty() ||
121 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
125 tmpdit.forwardInset();
132 /// Looks for next inset with one of the given codes.
133 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
137 DocIterator tmpdit = dit;
138 tmpdit.forwardInset();
143 Inset const * inset = tmpdit.nextInset();
145 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
146 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
150 if (!findNextInset(tmpdit, codes, contents)) {
151 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
152 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
153 if (!findNextInset(tmpdit, codes, contents))
164 /// Looks for next inset with the given code
165 void findInset(DocIterator & dit, InsetCode code, bool same_content)
167 findInset(dit, vector<InsetCode>(1, code), same_content);
171 /// Moves cursor to the next inset with one of the given codes.
172 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
175 Cursor tmpcur = bv->cursor();
176 if (!findInset(tmpcur, codes, same_content)) {
177 bv->cursor().message(_("No more insets"));
181 tmpcur.clearSelection();
182 bv->setCursor(tmpcur);
187 /// Moves cursor to the next inset with given code.
188 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
190 gotoInset(bv, vector<InsetCode>(1, code), same_content);
194 /// A map from a Text to the associated text metrics
195 typedef map<Text const *, TextMetrics> TextMetricsCache;
197 enum ScreenUpdateStrategy {
207 /////////////////////////////////////////////////////////////////////
211 /////////////////////////////////////////////////////////////////////
213 struct BufferView::Private
215 Private(BufferView & bv): wh_(0), cursor_(bv),
216 anchor_pit_(0), anchor_ypos_(0),
217 inlineCompletionUniqueChars_(0),
218 last_inset_(0), gui_(0)
222 ScrollbarParameters scrollbarParameters_;
224 ScreenUpdateStrategy update_strategy_;
226 CoordCache coord_cache_;
228 /// Estimated average par height for scrollbar.
230 /// this is used to handle XSelection events in the right manner.
239 pit_type anchor_pit_;
243 vector<int> par_height_;
246 DocIterator inlineCompletionPos_;
248 docstring inlineCompletion_;
250 size_t inlineCompletionUniqueChars_;
252 /// keyboard mapping object.
255 /// last visited inset.
256 /** kept to send setMouseHover(false).
257 * Not owned, so don't delete.
261 mutable TextMetricsCache text_metrics_;
264 /** Not owned, so don't delete.
266 frontend::GuiBufferViewDelegate * gui_;
268 /// Cache for Find Next
269 FuncRequest search_request_cache_;
273 BufferView::BufferView(Buffer & buf)
274 : width_(0), height_(0), full_screen_(false), buffer_(buf), d(new Private(*this))
276 d->xsel_cache_.set = false;
277 d->intl_.initKeyMapper(lyxrc.use_kbmap);
279 d->cursor_.push(buffer_.inset());
280 d->cursor_.resetAnchor();
281 d->cursor_.setCurrentFont();
283 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
284 graphics::Previews::get().generateBufferPreviews(buffer_);
288 BufferView::~BufferView()
290 // current buffer is going to be switched-off, save cursor pos
291 // Ideally, the whole cursor stack should be saved, but session
292 // currently can only handle bottom (whole document) level pit and pos.
293 // That is to say, if a cursor is in a nested inset, it will be
294 // restore to the left of the top level inset.
295 LastFilePosSection::FilePos fp;
296 fp.pit = d->cursor_.bottom().pit();
297 fp.pos = d->cursor_.bottom().pos();
298 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
304 int BufferView::rightMargin() const
306 // The additional test for the case the outliner is opened.
308 !lyxrc.full_screen_limit ||
309 width_ < lyxrc.full_screen_width + 20)
312 return (width_ - lyxrc.full_screen_width) / 2;
316 int BufferView::leftMargin() const
318 return rightMargin();
322 bool BufferView::isTopScreen() const
324 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
328 bool BufferView::isBottomScreen() const
330 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
334 Intl & BufferView::getIntl()
340 Intl const & BufferView::getIntl() const
346 CoordCache & BufferView::coordCache()
348 return d->coord_cache_;
352 CoordCache const & BufferView::coordCache() const
354 return d->coord_cache_;
358 Buffer & BufferView::buffer()
364 Buffer const & BufferView::buffer() const
370 bool BufferView::fitCursor()
372 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
373 frontend::FontMetrics const & fm =
374 theFontMetrics(d->cursor_.getFont().fontInfo());
375 int const asc = fm.maxAscent();
376 int const des = fm.maxDescent();
377 Point const p = getPos(d->cursor_, d->cursor_.boundary());
378 if (p.y_ - asc >= 0 && p.y_ + des < height_)
385 void BufferView::processUpdateFlags(Update::flags flags)
387 // last_inset_ points to the last visited inset. This pointer may become
388 // invalid because of keyboard editing. Since all such operations
389 // causes screen update(), I reset last_inset_ to avoid such a problem.
391 // This is close to a hot-path.
392 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
393 << "[fitcursor = " << (flags & Update::FitCursor)
394 << ", forceupdate = " << (flags & Update::Force)
395 << ", singlepar = " << (flags & Update::SinglePar)
396 << "] buffer: " << &buffer_);
398 buffer_.updateMacros();
400 // Now do the first drawing step if needed. This consists on updating
401 // the CoordCache in updateMetrics().
402 // The second drawing step is done in WorkArea::redraw() if needed.
404 // Case when no explicit update is requested.
406 // no need to redraw anything.
407 d->update_strategy_ = NoScreenUpdate;
411 if (flags == Update::Decoration) {
412 d->update_strategy_ = DecorationUpdate;
417 if (flags == Update::FitCursor
418 || flags == (Update::Decoration | Update::FitCursor)) {
419 // tell the frontend to update the screen if needed.
424 if (flags & Update::Decoration) {
425 d->update_strategy_ = DecorationUpdate;
429 // no screen update is needed.
430 d->update_strategy_ = NoScreenUpdate;
434 bool const full_metrics = flags & Update::Force || !singleParUpdate();
437 // We have to update the full screen metrics.
440 if (!(flags & Update::FitCursor)) {
441 // Nothing to do anymore. Trigger a redraw and return
446 // updateMetrics() does not update paragraph position
447 // This is done at draw() time. So we need a redraw!
451 // The cursor is off screen so ensure it is visible.
458 void BufferView::updateScrollbar()
463 // We prefer fixed size line scrolling.
464 d->scrollbarParameters_.single_step = defaultRowHeight();
465 // We prefer full screen page scrolling.
466 d->scrollbarParameters_.page_step = height_;
468 Text & t = buffer_.text();
469 TextMetrics & tm = d->text_metrics_[&t];
471 LYXERR(Debug::GUI, " Updating scrollbar: height: "
472 << t.paragraphs().size()
473 << " curr par: " << d->cursor_.bottom().pit()
474 << " default height " << defaultRowHeight());
476 size_t const parsize = t.paragraphs().size();
477 if (d->par_height_.size() != parsize) {
478 d->par_height_.clear();
479 // FIXME: We assume a default paragraph height of 2 rows. This
480 // should probably be pondered with the screen width.
481 d->par_height_.resize(parsize, defaultRowHeight() * 2);
484 // Look at paragraph heights on-screen
485 pair<pit_type, ParagraphMetrics const *> first = tm.first();
486 pair<pit_type, ParagraphMetrics const *> last = tm.last();
487 for (pit_type pit = first.first; pit <= last.first; ++pit) {
488 d->par_height_[pit] = tm.parMetrics(pit).height();
489 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
490 << d->par_height_[pit]);
493 int top_pos = first.second->position() - first.second->ascent();
494 int bottom_pos = last.second->position() + last.second->descent();
495 bool first_visible = first.first == 0 && top_pos >= 0;
496 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
497 if (first_visible && last_visible) {
498 d->scrollbarParameters_.min = 0;
499 d->scrollbarParameters_.max = 0;
503 d->scrollbarParameters_.min = top_pos;
504 for (size_t i = 0; i != size_t(first.first); ++i)
505 d->scrollbarParameters_.min -= d->par_height_[i];
506 d->scrollbarParameters_.max = bottom_pos;
507 for (size_t i = last.first + 1; i != parsize; ++i)
508 d->scrollbarParameters_.max += d->par_height_[i];
510 d->scrollbarParameters_.position = 0;
511 // The reference is the top position so we remove one page.
512 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
516 ScrollbarParameters const & BufferView::scrollbarParameters() const
518 return d->scrollbarParameters_;
522 docstring BufferView::toolTip(int x, int y) const
524 // Get inset under mouse, if there is one.
525 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
527 // No inset, no tooltip...
529 return covering_inset->toolTip(*this, x, y);
533 docstring BufferView::contextMenu(int x, int y) const
535 // Get inset under mouse, if there is one.
536 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
538 return covering_inset->contextMenu(*this, x, y);
540 return buffer_.inset().contextMenu(*this, x, y);
544 void BufferView::scrollDocView(int value)
546 int const offset = value - d->scrollbarParameters_.position;
547 // If the offset is less than 2 screen height, prefer to scroll instead.
548 if (abs(offset) <= 2 * height_) {
553 // cut off at the top
554 if (value <= d->scrollbarParameters_.min) {
555 DocIterator dit = doc_iterator_begin(buffer_.inset());
557 LYXERR(Debug::SCROLLING, "scroll to top");
561 // cut off at the bottom
562 if (value >= d->scrollbarParameters_.max) {
563 DocIterator dit = doc_iterator_end(buffer_.inset());
566 LYXERR(Debug::SCROLLING, "scroll to bottom");
570 // find paragraph at target position
571 int par_pos = d->scrollbarParameters_.min;
573 for (; i != int(d->par_height_.size()); ++i) {
574 par_pos += d->par_height_[i];
575 if (par_pos >= value)
579 if (par_pos < value) {
580 // It seems we didn't find the correct pit so stay on the safe side and
582 LYXERR0("scrolling position not found!");
583 scrollDocView(d->scrollbarParameters_.max);
587 DocIterator dit = doc_iterator_begin(buffer_.inset());
589 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
594 // FIXME: this method is not working well.
595 void BufferView::setCursorFromScrollbar()
597 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
599 int const height = 2 * defaultRowHeight();
600 int const first = height;
601 int const last = height_ - height;
602 Cursor & cur = d->cursor_;
604 switch (cursorStatus(cur)) {
606 // We reset the cursor because cursorStatus() does not
607 // work when the cursor is within mathed.
608 cur.reset(buffer_.inset());
609 tm.setCursorFromCoordinates(cur, 0, first);
610 cur.clearSelection();
613 // We reset the cursor because cursorStatus() does not
614 // work when the cursor is within mathed.
615 cur.reset(buffer_.inset());
616 tm.setCursorFromCoordinates(cur, 0, last);
617 cur.clearSelection();
620 int const y = getPos(cur, cur.boundary()).y_;
621 int const newy = min(last, max(y, first));
623 cur.reset(buffer_.inset());
624 tm.setCursorFromCoordinates(cur, 0, newy);
630 Change const BufferView::getCurrentChange() const
632 if (!d->cursor_.selection())
633 return Change(Change::UNCHANGED);
635 DocIterator dit = d->cursor_.selectionBegin();
636 return dit.paragraph().lookupChange(dit.pos());
640 // this could be used elsewhere as well?
641 // FIXME: This does not work within mathed!
642 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
644 Point const p = getPos(dit, dit.boundary());
647 if (p.y_ > workHeight())
653 void BufferView::saveBookmark(unsigned int idx)
655 // tenatively save bookmark, id and pos will be used to
656 // acturately locate a bookmark in a 'live' lyx session.
657 // pit and pos will be updated with bottom level pit/pos
659 LyX::ref().session().bookmarks().save(
661 d->cursor_.bottom().pit(),
662 d->cursor_.bottom().pos(),
663 d->cursor_.paragraph().id(),
668 // emit message signal.
669 message(_("Save bookmark"));
673 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
674 int top_id, pos_type top_pos)
676 bool success = false;
679 d->cursor_.clearSelection();
681 // if a valid par_id is given, try it first
682 // This is the case for a 'live' bookmark when unique paragraph ID
683 // is used to track bookmarks.
685 dit = buffer_.getParFromID(top_id);
687 dit.pos() = min(dit.paragraph().size(), top_pos);
688 // Some slices of the iterator may not be
689 // reachable (e.g. closed collapsable inset)
690 // so the dociterator may need to be
691 // shortened. Otherwise, setCursor may crash
692 // lyx when the cursor can not be set to these
694 size_t const n = dit.depth();
695 for (size_t i = 0; i < n; ++i)
696 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
704 // if top_id == 0, or searching through top_id failed
705 // This is the case for a 'restored' bookmark when only bottom
706 // (document level) pit was saved. Because of this, bookmark
707 // restoration is inaccurate. If a bookmark was within an inset,
708 // it will be restored to the left of the outmost inset that contains
710 if (bottom_pit < int(buffer_.paragraphs().size())) {
711 dit = doc_iterator_begin(buffer_.inset());
713 dit.pit() = bottom_pit;
714 dit.pos() = min(bottom_pos, dit.paragraph().size());
719 // Note: only bottom (document) level pit is set.
721 // set the current font.
722 d->cursor_.setCurrentFont();
723 // To center the screen on this new position we need the
724 // paragraph position which is computed at draw() time.
725 // So we need a redraw!
735 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
737 if (lyxrc.rtl_support) {
738 if (d->cursor_.real_current_font.isRightToLeft()) {
739 if (d->intl_.keymap == Intl::PRIMARY)
740 d->intl_.keyMapSec();
742 if (d->intl_.keymap == Intl::SECONDARY)
743 d->intl_.keyMapPrim();
747 d->intl_.getTransManager().translateAndInsert(c, t, cur);
751 int BufferView::workWidth() const
757 void BufferView::showCursor()
759 showCursor(d->cursor_);
763 void BufferView::showCursor(DocIterator const & dit)
765 // We are not properly started yet, delay until resizing is
770 LYXERR(Debug::SCROLLING, "recentering!");
772 CursorSlice const & bot = dit.bottom();
773 TextMetrics & tm = d->text_metrics_[bot.text()];
775 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
776 int bot_pit = bot.pit();
777 if (bot_pit > max_pit) {
778 // FIXME: Why does this happen?
779 LYXERR0("bottom pit is greater that max pit: "
780 << bot_pit << " > " << max_pit);
784 if (bot_pit == tm.first().first - 1)
785 tm.newParMetricsUp();
786 else if (bot_pit == tm.last().first + 1)
787 tm.newParMetricsDown();
789 if (tm.contains(bot_pit)) {
790 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
791 LASSERT(!pm.rows().empty(), /**/);
792 // FIXME: smooth scrolling doesn't work in mathed.
793 CursorSlice const & cs = dit.innerTextSlice();
794 int offset = coordOffset(dit, dit.boundary()).y_;
795 int ypos = pm.position() + offset;
796 Dimension const & row_dim =
797 pm.getRow(cs.pos(), dit.boundary()).dimension();
798 if (ypos - row_dim.ascent() < 0)
799 scrollUp(- ypos + row_dim.ascent());
800 else if (ypos + row_dim.descent() > height_)
801 scrollDown(ypos - height_ + row_dim.descent());
802 // else, nothing to do, the cursor is already visible so we just return.
806 // fix inline completion position
807 if (d->inlineCompletionPos_.fixIfBroken())
808 d->inlineCompletionPos_ = DocIterator();
810 tm.redoParagraph(bot_pit);
811 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
812 int offset = coordOffset(dit, dit.boundary()).y_;
814 d->anchor_pit_ = bot_pit;
815 CursorSlice const & cs = dit.innerTextSlice();
816 Dimension const & row_dim =
817 pm.getRow(cs.pos(), dit.boundary()).dimension();
819 if (d->anchor_pit_ == 0)
820 d->anchor_ypos_ = offset + pm.ascent();
821 else if (d->anchor_pit_ == max_pit)
822 d->anchor_ypos_ = height_ - offset - row_dim.descent();
824 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
831 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
835 Cursor & cur = d->cursor_;
837 switch (cmd.action) {
840 flag.setEnabled(buffer_.undo().hasUndoStack());
843 flag.setEnabled(buffer_.undo().hasRedoStack());
845 case LFUN_FILE_INSERT:
846 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
847 case LFUN_FILE_INSERT_PLAINTEXT:
848 case LFUN_BOOKMARK_SAVE:
849 // FIXME: Actually, these LFUNS should be moved to Text
850 flag.setEnabled(cur.inTexted());
852 case LFUN_FONT_STATE:
853 case LFUN_LABEL_INSERT:
854 case LFUN_INFO_INSERT:
855 case LFUN_INSET_EDIT:
856 case LFUN_PARAGRAPH_GOTO:
858 case LFUN_REFERENCE_NEXT:
860 case LFUN_WORD_REPLACE:
863 case LFUN_MARK_TOGGLE:
864 case LFUN_SCREEN_RECENTER:
865 case LFUN_BIBTEX_DATABASE_ADD:
866 case LFUN_BIBTEX_DATABASE_DEL:
867 case LFUN_STATISTICS:
868 flag.setEnabled(true);
871 case LFUN_NEXT_INSET_TOGGLE:
872 case LFUN_NEXT_INSET_MODIFY: {
873 // this is the real function we want to invoke
874 FuncRequest tmpcmd = cmd;
875 tmpcmd.action = (cmd.action == LFUN_NEXT_INSET_TOGGLE)
876 ? LFUN_INSET_TOGGLE : LFUN_INSET_MODIFY;
877 // if there is an inset at cursor, see whether it
878 // handles the lfun, other start from scratch
879 Inset * inset = cur.nextInset();
880 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
881 flag = lyx::getStatus(tmpcmd);
885 case LFUN_LABEL_GOTO: {
886 flag.setEnabled(!cmd.argument().empty()
887 || getInsetByCode<InsetRef>(cur, REF_CODE));
891 case LFUN_CHANGES_TRACK:
892 flag.setEnabled(true);
893 flag.setOnOff(buffer_.params().trackChanges);
896 case LFUN_CHANGES_OUTPUT:
897 flag.setEnabled(true);
898 flag.setOnOff(buffer_.params().outputChanges);
901 case LFUN_CHANGES_MERGE:
902 case LFUN_CHANGE_NEXT:
903 case LFUN_ALL_CHANGES_ACCEPT:
904 case LFUN_ALL_CHANGES_REJECT:
905 // TODO: context-sensitive enabling of LFUNs
906 // In principle, these command should only be enabled if there
907 // is a change in the document. However, without proper
908 // optimizations, this will inevitably result in poor performance.
909 flag.setEnabled(true);
912 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
913 flag.setOnOff(buffer_.params().compressed);
918 case LFUN_SCREEN_DOWN:
920 case LFUN_SCREEN_UP_SELECT:
921 case LFUN_SCREEN_DOWN_SELECT:
922 flag.setEnabled(true);
925 case LFUN_LAYOUT_TABULAR:
926 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
930 flag.setEnabled(!cur.inset().forceEmptyLayout(cur.idx()));
933 case LFUN_LAYOUT_PARAGRAPH:
934 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
937 case LFUN_INSET_SETTINGS: {
938 InsetCode code = cur.inset().lyxCode();
939 if (cmd.getArg(0) == insetName(code)) {
940 flag.setEnabled(true);
944 InsetCode next_code = cur.nextInset()
945 ? cur.nextInset()->lyxCode() : NO_CODE;
946 //FIXME: remove these special cases:
957 enable = (cmd.argument().empty() ||
958 cmd.getArg(0) == insetName(next_code));
963 flag.setEnabled(enable);
967 case LFUN_DIALOG_SHOW_NEW_INSET:
968 flag.setEnabled(cur.inset().lyxCode() != ERT_CODE &&
969 cur.inset().lyxCode() != LISTINGS_CODE);
970 if (cur.inset().lyxCode() == CAPTION_CODE) {
972 if (cur.inset().getStatus(cur, cmd, flag))
977 case LFUN_BRANCH_ACTIVATE:
978 case LFUN_BRANCH_DEACTIVATE: {
980 docstring const branchName = cmd.argument();
981 if (!branchName.empty())
982 enable = buffer_.params().branchlist().find(branchName);
983 flag.setEnabled(enable);
988 flag.setEnabled(false);
995 bool BufferView::dispatch(FuncRequest const & cmd)
997 //lyxerr << [ cmd = " << cmd << "]" << endl;
999 // Make sure that the cached BufferView is correct.
1000 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1001 << " arg[" << to_utf8(cmd.argument()) << ']'
1002 << " x[" << cmd.x << ']'
1003 << " y[" << cmd.y << ']'
1004 << " button[" << cmd.button() << ']');
1006 Cursor & cur = d->cursor_;
1008 switch (cmd.action) {
1011 cur.message(_("Undo"));
1012 cur.clearSelection();
1013 if (!cur.textUndo())
1014 cur.message(_("No further undo information"));
1016 processUpdateFlags(Update::Force | Update::FitCursor);
1020 cur.message(_("Redo"));
1021 cur.clearSelection();
1022 if (!cur.textRedo())
1023 cur.message(_("No further redo information"));
1025 processUpdateFlags(Update::Force | Update::FitCursor);
1028 case LFUN_FONT_STATE:
1029 cur.message(cur.currentState());
1032 case LFUN_BOOKMARK_SAVE:
1033 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1036 case LFUN_LABEL_GOTO: {
1037 docstring label = cmd.argument();
1038 if (label.empty()) {
1040 getInsetByCode<InsetRef>(d->cursor_,
1043 label = inset->getParam("reference");
1044 // persistent=false: use temp_bookmark
1054 case LFUN_INSET_EDIT: {
1055 FuncRequest fr(cmd);
1056 // if there is an inset at cursor, see whether it
1058 Inset * inset = cur.nextInset();
1060 inset->dispatch(cur, fr);
1061 // if it did not work, try the underlying inset.
1062 if (!inset || !cur.result().dispatched())
1065 if (!cur.result().dispatched())
1066 // It did not work too; no action needed.
1070 case LFUN_PARAGRAPH_GOTO: {
1071 int const id = convert<int>(cmd.getArg(0));
1072 int const pos = convert<int>(cmd.getArg(1));
1074 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1075 b = theBufferList().next(b)) {
1077 DocIterator dit = b->getParFromID(id);
1079 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1083 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1084 << " found in buffer `"
1085 << b->absFileName() << "'.");
1087 if (b == &buffer_) {
1091 processUpdateFlags(Update::Force | Update::FitCursor);
1093 // Switch to other buffer view and resend cmd
1094 theLyXFunc().dispatch(FuncRequest(
1095 LFUN_BUFFER_SWITCH, b->absFileName()));
1096 theLyXFunc().dispatch(cmd);
1103 case LFUN_NOTE_NEXT:
1104 gotoInset(this, NOTE_CODE, false);
1107 case LFUN_REFERENCE_NEXT: {
1108 vector<InsetCode> tmp;
1109 tmp.push_back(LABEL_CODE);
1110 tmp.push_back(REF_CODE);
1111 gotoInset(this, tmp, true);
1115 case LFUN_CHANGES_TRACK:
1116 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1119 case LFUN_CHANGES_OUTPUT:
1120 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1121 if (buffer_.params().outputChanges) {
1122 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1123 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1124 LaTeXFeatures::isAvailable("xcolor");
1126 if (!dvipost && !xcolorsoul) {
1127 Alert::warning(_("Changes not shown in LaTeX output"),
1128 _("Changes will not be highlighted in LaTeX output, "
1129 "because neither dvipost nor xcolor/soul are installed.\n"
1130 "Please install these packages or redefine "
1131 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1132 } else if (!xcolorsoul) {
1133 Alert::warning(_("Changes not shown in LaTeX output"),
1134 _("Changes will not be highlighted in LaTeX output "
1135 "when using pdflatex, because xcolor and soul are not installed.\n"
1136 "Please install both packages or redefine "
1137 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1142 case LFUN_CHANGE_NEXT:
1143 findNextChange(this);
1146 case LFUN_CHANGES_MERGE:
1147 if (findNextChange(this))
1148 showDialog("changes");
1151 case LFUN_ALL_CHANGES_ACCEPT:
1152 // select complete document
1153 d->cursor_.reset(buffer_.inset());
1154 d->cursor_.selHandle(true);
1155 buffer_.text().cursorBottom(d->cursor_);
1156 // accept everything in a single step to support atomic undo
1157 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1160 case LFUN_ALL_CHANGES_REJECT:
1161 // select complete document
1162 d->cursor_.reset(buffer_.inset());
1163 d->cursor_.selHandle(true);
1164 buffer_.text().cursorBottom(d->cursor_);
1165 // reject everything in a single step to support atomic undo
1166 // Note: reject does not work recursively; the user may have to repeat the operation
1167 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1170 case LFUN_WORD_FIND: {
1171 FuncRequest req = cmd;
1172 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1173 req = d->search_request_cache_;
1174 if (find(this, req))
1177 message(_("String not found!"));
1178 d->search_request_cache_ = req;
1182 case LFUN_WORD_REPLACE: {
1183 bool has_deleted = false;
1184 if (cur.selection()) {
1185 DocIterator beg = cur.selectionBegin();
1186 DocIterator end = cur.selectionEnd();
1187 if (beg.pit() == end.pit()) {
1188 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1189 if (cur.paragraph().isDeleted(p))
1194 replace(this, cmd, has_deleted);
1199 cur.clearSelection();
1201 cur.message(from_utf8(N_("Mark off")));
1205 cur.clearSelection();
1208 cur.message(from_utf8(N_("Mark on")));
1211 case LFUN_MARK_TOGGLE:
1212 cur.clearSelection();
1215 cur.message(from_utf8(N_("Mark removed")));
1218 cur.message(from_utf8(N_("Mark set")));
1223 case LFUN_SCREEN_RECENTER:
1227 case LFUN_BIBTEX_DATABASE_ADD: {
1228 Cursor tmpcur = d->cursor_;
1229 findInset(tmpcur, BIBTEX_CODE, false);
1230 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1233 if (inset->addDatabase(cmd.argument()))
1234 buffer_.updateBibfilesCache();
1239 case LFUN_BIBTEX_DATABASE_DEL: {
1240 Cursor tmpcur = d->cursor_;
1241 findInset(tmpcur, BIBTEX_CODE, false);
1242 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1245 if (inset->delDatabase(cmd.argument()))
1246 buffer_.updateBibfilesCache();
1251 case LFUN_STATISTICS: {
1252 DocIterator from, to;
1253 if (cur.selection()) {
1254 from = cur.selectionBegin();
1255 to = cur.selectionEnd();
1257 from = doc_iterator_begin(buffer_.inset());
1258 to = doc_iterator_end(buffer_.inset());
1260 int const words = countWords(from, to);
1261 int const chars = countChars(from, to, false);
1262 int const chars_blanks = countChars(from, to, true);
1264 if (cur.selection())
1265 message = _("Statistics for the selection:");
1267 message = _("Statistics for the document:");
1270 message += bformat(_("%1$d words"), words);
1272 message += _("One word");
1274 if (chars_blanks != 1)
1275 message += bformat(_("%1$d characters (including blanks)"),
1278 message += _("One character (including blanks)");
1281 message += bformat(_("%1$d characters (excluding blanks)"),
1284 message += _("One character (excluding blanks)");
1286 Alert::information(_("Statistics"), message);
1290 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1291 // turn compression on/off
1292 buffer_.params().compressed = !buffer_.params().compressed;
1295 case LFUN_NEXT_INSET_TOGGLE: {
1296 // create the the real function we want to invoke
1297 FuncRequest tmpcmd = cmd;
1298 tmpcmd.action = LFUN_INSET_TOGGLE;
1299 // if there is an inset at cursor, see whether it
1301 Inset * inset = cur.nextInset();
1303 if (inset->isActive()) {
1304 Cursor tmpcur = cur;
1305 tmpcur.pushBackward(*inset);
1306 inset->dispatch(tmpcur, tmpcmd);
1307 if (tmpcur.result().dispatched())
1310 inset->dispatch(cur, tmpcmd);
1312 // if it did not work, try the underlying inset.
1313 if (!inset || !cur.result().dispatched())
1314 cur.dispatch(tmpcmd);
1316 if (!cur.result().dispatched())
1317 // It did not work too; no action needed.
1319 cur.clearSelection();
1320 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1324 case LFUN_NEXT_INSET_MODIFY: {
1325 // create the the real function we want to invoke
1326 FuncRequest tmpcmd = cmd;
1327 tmpcmd.action = LFUN_INSET_MODIFY;
1328 // if there is an inset at cursor, see whether it
1330 Inset * inset = cur.nextInset();
1332 inset->dispatch(cur, tmpcmd);
1333 // if it did not work, try the underlying inset.
1334 if (!inset || !cur.result().dispatched())
1335 cur.dispatch(tmpcmd);
1337 if (!cur.result().dispatched())
1338 // It did not work too; no action needed.
1340 cur.clearSelection();
1341 processUpdateFlags(Update::Force | Update::FitCursor);
1345 case LFUN_SCREEN_UP:
1346 case LFUN_SCREEN_DOWN: {
1347 Point p = getPos(cur, cur.boundary());
1348 if (p.y_ < 0 || p.y_ > height_) {
1349 // The cursor is off-screen so recenter before proceeding.
1351 p = getPos(cur, cur.boundary());
1353 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1354 cur.reset(buffer_.inset());
1355 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1356 //FIXME: what to do with cur.x_target()?
1365 case LFUN_SCREEN_UP_SELECT: {
1366 cur.selHandle(true);
1367 if (isTopScreen()) {
1368 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1372 int y = getPos(cur, cur.boundary()).y_;
1373 int const ymin = y - height_ + defaultRowHeight();
1374 while (y > ymin && cur.up())
1375 y = getPos(cur, cur.boundary()).y_;
1378 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1382 case LFUN_SCREEN_DOWN_SELECT: {
1383 cur.selHandle(true);
1384 if (isBottomScreen()) {
1385 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1389 int y = getPos(cur, cur.boundary()).y_;
1390 int const ymax = y + height_ - defaultRowHeight();
1391 while (y < ymax && cur.down())
1392 y = getPos(cur, cur.boundary()).y_;
1395 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1399 case LFUN_BRANCH_ACTIVATE:
1400 case LFUN_BRANCH_DEACTIVATE:
1401 buffer_.dispatch(cmd);
1402 processUpdateFlags(Update::Force);
1413 docstring const BufferView::requestSelection()
1415 Cursor & cur = d->cursor_;
1417 if (!cur.selection()) {
1418 d->xsel_cache_.set = false;
1422 if (!d->xsel_cache_.set ||
1423 cur.top() != d->xsel_cache_.cursor ||
1424 cur.anchor_.top() != d->xsel_cache_.anchor)
1426 d->xsel_cache_.cursor = cur.top();
1427 d->xsel_cache_.anchor = cur.anchor_.top();
1428 d->xsel_cache_.set = cur.selection();
1429 return cur.selectionAsString(false);
1435 void BufferView::clearSelection()
1437 d->cursor_.clearSelection();
1438 // Clear the selection buffer. Otherwise a subsequent
1439 // middle-mouse-button paste would use the selection buffer,
1440 // not the more current external selection.
1441 cap::clearSelection();
1442 d->xsel_cache_.set = false;
1443 // The buffer did not really change, but this causes the
1444 // redraw we need because we cleared the selection above.
1449 void BufferView::resize(int width, int height)
1451 // Update from work area
1455 // Clear the paragraph height cache.
1456 d->par_height_.clear();
1457 // Redo the metrics.
1462 Inset const * BufferView::getCoveringInset(Text const & text,
1465 TextMetrics & tm = d->text_metrics_[&text];
1466 Inset * inset = tm.checkInsetHit(x, y);
1470 if (!inset->descendable())
1471 // No need to go further down if the inset is not
1475 size_t cell_number = inset->nargs();
1476 // Check all the inner cell.
1477 for (size_t i = 0; i != cell_number; ++i) {
1478 Text const * inner_text = inset->getText(i);
1481 Inset const * inset_deeper =
1482 getCoveringInset(*inner_text, x, y);
1484 return inset_deeper;
1492 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1494 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1496 // This is only called for mouse related events including
1497 // LFUN_FILE_OPEN generated by drag-and-drop.
1498 FuncRequest cmd = cmd0;
1500 Cursor old = cursor();
1502 cur.push(buffer_.inset());
1503 cur.selection() = d->cursor_.selection();
1505 // Either the inset under the cursor or the
1506 // surrounding Text will handle this event.
1508 // make sure we stay within the screen...
1509 cmd.y = min(max(cmd.y, -1), height_);
1511 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1513 // Get inset under mouse, if there is one.
1514 Inset const * covering_inset =
1515 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1516 if (covering_inset == d->last_inset_)
1517 // Same inset, no need to do anything...
1520 bool need_redraw = false;
1521 // const_cast because of setMouseHover().
1522 Inset * inset = const_cast<Inset *>(covering_inset);
1524 // Remove the hint on the last hovered inset (if any).
1525 need_redraw |= d->last_inset_->setMouseHover(false);
1527 // Highlighted the newly hovered inset (if any).
1528 need_redraw |= inset->setMouseHover(true);
1529 d->last_inset_ = inset;
1533 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1534 << cmd.x << ", " << cmd.y << ")");
1536 d->update_strategy_ = DecorationUpdate;
1538 // This event (moving without mouse click) is not passed further.
1539 // This should be changed if it is further utilized.
1544 // Build temporary cursor.
1545 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1547 // Put anchor at the same position.
1550 // Try to dispatch to an non-editable inset near this position
1551 // via the temp cursor. If the inset wishes to change the real
1552 // cursor it has to do so explicitly by using
1553 // cur.bv().cursor() = cur; (or similar)
1555 inset->dispatch(cur, cmd);
1557 // Now dispatch to the temporary cursor. If the real cursor should
1558 // be modified, the inset's dispatch has to do so explicitly.
1559 if (!inset || !cur.result().dispatched())
1562 // Notify left insets
1565 bool badcursor = notifyCursorLeaves(old, cur);
1567 cursor().fixIfBroken();
1570 // Do we have a selection?
1571 theSelection().haveSelection(cursor().selection());
1573 // If the command has been dispatched,
1574 if (cur.result().dispatched() || cur.result().update())
1575 processUpdateFlags(cur.result().update());
1579 void BufferView::lfunScroll(FuncRequest const & cmd)
1581 string const scroll_type = cmd.getArg(0);
1582 int const scroll_step =
1583 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1584 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1585 if (scroll_step == 0)
1587 string const scroll_quantity = cmd.getArg(1);
1588 if (scroll_quantity == "up")
1589 scrollUp(scroll_step);
1590 else if (scroll_quantity == "down")
1591 scrollDown(scroll_step);
1593 int const scroll_value = convert<int>(scroll_quantity);
1595 scroll(scroll_step * scroll_value);
1600 void BufferView::scroll(int y)
1609 void BufferView::scrollDown(int offset)
1611 Text * text = &buffer_.text();
1612 TextMetrics & tm = d->text_metrics_[text];
1613 int ymax = height_ + offset;
1615 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1616 int bottom_pos = last.second->position() + last.second->descent();
1617 if (last.first + 1 == int(text->paragraphs().size())) {
1618 if (bottom_pos <= height_)
1620 offset = min(offset, bottom_pos - height_);
1623 if (bottom_pos > ymax)
1625 tm.newParMetricsDown();
1627 d->anchor_ypos_ -= offset;
1633 void BufferView::scrollUp(int offset)
1635 Text * text = &buffer_.text();
1636 TextMetrics & tm = d->text_metrics_[text];
1637 int ymin = - offset;
1639 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1640 int top_pos = first.second->position() - first.second->ascent();
1641 if (first.first == 0) {
1644 offset = min(offset, - top_pos);
1649 tm.newParMetricsUp();
1651 d->anchor_ypos_ += offset;
1657 void BufferView::setCursorFromRow(int row)
1662 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1664 d->cursor_.reset(buffer_.inset());
1666 buffer_.text().setCursor(d->cursor_, 0, 0);
1668 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1672 void BufferView::gotoLabel(docstring const & label)
1674 Toc & toc = buffer().tocBackend().toc("label");
1675 TocIterator toc_it = toc.begin();
1676 TocIterator end = toc.end();
1677 for (; toc_it != end; ++toc_it) {
1678 if (label == toc_it->str())
1679 dispatch(toc_it->action());
1681 //FIXME: We could do a bit more searching thanks to this:
1682 //InsetLabel const * inset = buffer_.insetLabel(label);
1686 TextMetrics const & BufferView::textMetrics(Text const * t) const
1688 return const_cast<BufferView *>(this)->textMetrics(t);
1692 TextMetrics & BufferView::textMetrics(Text const * t)
1694 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1695 if (tmc_it == d->text_metrics_.end()) {
1696 tmc_it = d->text_metrics_.insert(
1697 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1699 return tmc_it->second;
1703 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1706 return textMetrics(t).parMetrics(pit);
1710 int BufferView::workHeight() const
1716 void BufferView::setCursor(DocIterator const & dit)
1718 size_t const n = dit.depth();
1719 for (size_t i = 0; i < n; ++i)
1720 dit[i].inset().edit(d->cursor_, true);
1722 d->cursor_.setCursor(dit);
1723 d->cursor_.selection() = false;
1727 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1729 // Would be wrong to delete anything if we have a selection.
1730 if (cur.selection())
1733 bool need_anchor_change = false;
1734 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1735 need_anchor_change);
1737 if (need_anchor_change)
1745 updateLabels(buffer_);
1753 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1755 LASSERT(&cur.bv() == this, /**/);
1758 // this event will clear selection so we save selection for
1759 // persistent selection
1760 cap::saveSelection(cursor());
1762 // Has the cursor just left the inset?
1763 bool badcursor = false;
1764 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1766 d->cursor_.fixIfBroken();
1767 badcursor = notifyCursorLeaves(d->cursor_, cur);
1772 // FIXME: shift-mouse selection doesn't work well across insets.
1773 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1775 // do the dEPM magic if needed
1776 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1777 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1778 // the leftinset bool would not be necessary (badcursor instead).
1779 bool update = leftinset;
1780 if (!do_selection && !badcursor && d->cursor_.inTexted())
1781 update |= checkDepm(cur, d->cursor_);
1783 d->cursor_.setCursor(cur);
1784 d->cursor_.boundary(cur.boundary());
1786 d->cursor_.setSelection();
1788 d->cursor_.clearSelection();
1790 d->cursor_.finishUndo();
1791 d->cursor_.setCurrentFont();
1796 void BufferView::putSelectionAt(DocIterator const & cur,
1797 int length, bool backwards)
1799 d->cursor_.clearSelection();
1805 d->cursor_.pos() += length;
1806 d->cursor_.setSelection(d->cursor_, -length);
1808 d->cursor_.setSelection(d->cursor_, length);
1810 // Ensure a redraw happens in any case because the new selection could
1811 // possibly be on the same screen as the previous selection.
1812 processUpdateFlags(Update::Force | Update::FitCursor);
1816 Cursor & BufferView::cursor()
1822 Cursor const & BufferView::cursor() const
1828 pit_type BufferView::anchor_ref() const
1830 return d->anchor_pit_;
1834 bool BufferView::singleParUpdate()
1836 Text & buftext = buffer_.text();
1837 pit_type const bottom_pit = d->cursor_.bottom().pit();
1838 TextMetrics & tm = textMetrics(&buftext);
1839 int old_height = tm.parMetrics(bottom_pit).height();
1841 // make sure inline completion pointer is ok
1842 if (d->inlineCompletionPos_.fixIfBroken())
1843 d->inlineCompletionPos_ = DocIterator();
1845 // In Single Paragraph mode, rebreak only
1846 // the (main text, not inset!) paragraph containing the cursor.
1847 // (if this paragraph contains insets etc., rebreaking will
1848 // recursively descend)
1849 tm.redoParagraph(bottom_pit);
1850 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1851 if (pm.height() != old_height)
1852 // Paragraph height has changed so we cannot proceed to
1853 // the singlePar optimisation.
1856 d->update_strategy_ = SingleParUpdate;
1858 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1859 << " y2: " << pm.position() + pm.descent()
1860 << " pit: " << bottom_pit
1861 << " singlepar: 1");
1866 void BufferView::updateMetrics()
1868 Text & buftext = buffer_.text();
1869 pit_type const npit = int(buftext.paragraphs().size());
1871 // Clear out the position cache in case of full screen redraw,
1872 d->coord_cache_.clear();
1874 // Clear out paragraph metrics to avoid having invalid metrics
1875 // in the cache from paragraphs not relayouted below
1876 // The complete text metrics will be redone.
1877 d->text_metrics_.clear();
1879 TextMetrics & tm = textMetrics(&buftext);
1881 // make sure inline completion pointer is ok
1882 if (d->inlineCompletionPos_.fixIfBroken())
1883 d->inlineCompletionPos_ = DocIterator();
1885 if (d->anchor_pit_ >= npit)
1886 // The anchor pit must have been deleted...
1887 d->anchor_pit_ = npit - 1;
1889 // Rebreak anchor paragraph.
1890 tm.redoParagraph(d->anchor_pit_);
1891 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1894 if (d->anchor_pit_ == 0) {
1895 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
1897 // Complete buffer visible? Then it's easy.
1898 if (scrollRange == 0)
1899 d->anchor_ypos_ = anchor_pm.ascent();
1901 // FIXME: Some clever handling needed to show
1902 // the _first_ paragraph up to the top if the cursor is
1903 // in the first line.
1905 anchor_pm.setPosition(d->anchor_ypos_);
1907 LYXERR(Debug::PAINTING, "metrics: "
1908 << " anchor pit = " << d->anchor_pit_
1909 << " anchor ypos = " << d->anchor_ypos_);
1911 // Redo paragraphs above anchor if necessary.
1912 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1913 // We are now just above the anchor paragraph.
1914 pit_type pit1 = d->anchor_pit_ - 1;
1915 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1916 tm.redoParagraph(pit1);
1917 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1919 // Save the paragraph position in the cache.
1924 // Redo paragraphs below the anchor if necessary.
1925 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1926 // We are now just below the anchor paragraph.
1927 pit_type pit2 = d->anchor_pit_ + 1;
1928 for (; pit2 < npit && y2 <= height_; ++pit2) {
1929 tm.redoParagraph(pit2);
1930 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1932 // Save the paragraph position in the cache.
1937 LYXERR(Debug::PAINTING, "Metrics: "
1938 << " anchor pit = " << d->anchor_pit_
1939 << " anchor ypos = " << d->anchor_ypos_
1942 << " pit1 = " << pit1
1943 << " pit2 = " << pit2);
1945 d->update_strategy_ = FullScreenUpdate;
1947 if (lyxerr.debugging(Debug::WORKAREA)) {
1948 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1949 d->coord_cache_.dump();
1954 void BufferView::insertLyXFile(FileName const & fname)
1956 LASSERT(d->cursor_.inTexted(), /**/);
1958 // Get absolute path of file and add ".lyx"
1959 // to the filename if necessary
1960 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1962 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1963 // emit message signal.
1964 message(bformat(_("Inserting document %1$s..."), disp_fn));
1967 Buffer buf("", false);
1968 if (buf.loadLyXFile(filename)) {
1969 ErrorList & el = buffer_.errorList("Parse");
1970 // Copy the inserted document error list into the current buffer one.
1971 el = buf.errorList("Parse");
1972 buffer_.undo().recordUndo(d->cursor_);
1973 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1974 buf.params().documentClassPtr(), el);
1975 res = _("Document %1$s inserted.");
1977 res = _("Could not insert document %1$s");
1982 // emit message signal.
1983 message(bformat(res, disp_fn));
1984 buffer_.errors("Parse");
1988 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1994 // Addup contribution of nested insets, from inside to outside,
1995 // keeping the outer paragraph for a special handling below
1996 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1997 CursorSlice const & sl = dit[i];
2001 // get relative position inside sl.inset()
2002 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2004 // Make relative position inside of the edited inset relative to sl.inset()
2008 // In case of an RTL inset, the edited inset will be positioned to the left
2011 bool boundary_i = boundary && i + 1 == dit.depth();
2012 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2017 // remember width for the case that sl.inset() is positioned in an RTL inset
2018 if (i && dit[i - 1].text()) {
2019 // If this Inset is inside a Text Inset, retrieve the Dimension
2020 // from the containing text instead of using Inset::dimension() which
2021 // might not be implemented.
2022 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2023 // elimination of Inset::dim_ cache. This coordOffset() method needs
2024 // to be rewritten in light of the new design.
2025 Dimension const & dim = parMetrics(dit[i - 1].text(),
2026 dit[i - 1].pit()).insetDimension(&sl.inset());
2029 Dimension const dim = sl.inset().dimension(*this);
2033 //lyxerr << "Cursor::getPos, i: "
2034 // << i << " x: " << xx << " y: " << y << endl;
2037 // Add contribution of initial rows of outermost paragraph
2038 CursorSlice const & sl = dit[0];
2039 TextMetrics const & tm = textMetrics(sl.text());
2040 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2041 LASSERT(!pm.rows().empty(), /**/);
2042 y -= pm.rows()[0].ascent();
2044 // FIXME: document this mess
2046 if (sl.pos() > 0 && dit.depth() == 1) {
2048 if (pos && boundary)
2050 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2051 rend = pm.pos2row(pos);
2053 rend = pm.pos2row(sl.pos());
2055 size_t rend = pm.pos2row(sl.pos());
2057 for (size_t rit = 0; rit != rend; ++rit)
2058 y += pm.rows()[rit].height();
2059 y += pm.rows()[rend].ascent();
2061 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2063 // Make relative position from the nested inset now bufferview absolute.
2064 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2067 // In the RTL case place the nested inset at the left of the cursor in
2068 // the outer paragraph
2069 bool boundary_1 = boundary && 1 == dit.depth();
2070 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2078 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2080 CursorSlice const & bot = dit.bottom();
2081 TextMetrics const & tm = textMetrics(bot.text());
2082 if (!tm.contains(bot.pit()))
2083 return Point(-1, -1);
2085 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2086 p.y_ += tm.parMetrics(bot.pit()).position();
2091 void BufferView::draw(frontend::Painter & pain)
2093 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2094 Text & text = buffer_.text();
2095 TextMetrics const & tm = d->text_metrics_[&text];
2096 int const y = tm.first().second->position();
2097 PainterInfo pi(this, pain);
2099 switch (d->update_strategy_) {
2101 case NoScreenUpdate:
2102 // If no screen painting is actually needed, only some the different
2103 // coordinates of insets and paragraphs needs to be updated.
2104 pi.full_repaint = true;
2105 pi.pain.setDrawingEnabled(false);
2109 case SingleParUpdate:
2110 pi.full_repaint = false;
2111 // In general, only the current row of the outermost paragraph
2112 // will be redrawn. Particular cases where selection spans
2113 // multiple paragraph are correctly detected in TextMetrics.
2117 case DecorationUpdate:
2118 // FIXME: We should also distinguish DecorationUpdate to avoid text
2119 // drawing if possible. This is not possible to do easily right now
2120 // because of the single backing pixmap.
2122 case FullScreenUpdate:
2123 // The whole screen, including insets, will be refreshed.
2124 pi.full_repaint = true;
2126 // Clear background.
2127 pain.fillRectangle(0, 0, width_, height_,
2128 buffer_.inset().backgroundColor());
2133 // and possibly grey out below
2134 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2135 int const y2 = lastpm.second->position() + lastpm.second->descent();
2137 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2140 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2142 // The scrollbar needs an update.
2145 // Normalize anchor for next time
2146 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2147 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2148 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2149 ParagraphMetrics const & pm = tm.parMetrics(pit);
2150 if (pm.position() + pm.descent() > 0) {
2151 d->anchor_pit_ = pit;
2152 d->anchor_ypos_ = pm.position();
2156 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2157 << " anchor ypos = " << d->anchor_ypos_);
2161 void BufferView::message(docstring const & msg)
2164 d->gui_->message(msg);
2168 void BufferView::showDialog(string const & name)
2171 d->gui_->showDialog(name, string());
2175 void BufferView::showDialog(string const & name,
2176 string const & data, Inset * inset)
2179 d->gui_->showDialog(name, data, inset);
2183 void BufferView::updateDialog(string const & name, string const & data)
2186 d->gui_->updateDialog(name, data);
2190 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2196 // FIXME: Move this out of BufferView again
2197 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2199 if (!fname.isReadableFile()) {
2200 docstring const error = from_ascii(strerror(errno));
2201 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2202 docstring const text =
2203 bformat(_("Could not read the specified document\n"
2204 "%1$s\ndue to the error: %2$s"), file, error);
2205 Alert::error(_("Could not read file"), text);
2209 if (!fname.isReadableFile()) {
2210 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2211 docstring const text =
2212 bformat(_("%1$s\n is not readable."), file);
2213 Alert::error(_("Could not open file"), text);
2217 // FIXME UNICODE: We don't know the encoding of the file
2218 docstring file_content = fname.fileContents("UTF-8");
2219 if (file_content.empty()) {
2220 Alert::error(_("Reading not UTF-8 encoded file"),
2221 _("The file is not UTF-8 encoded.\n"
2222 "It will be read as local 8Bit-encoded.\n"
2223 "If this does not give the correct result\n"
2224 "then please change the encoding of the file\n"
2225 "to UTF-8 with a program other than LyX.\n"));
2226 file_content = fname.fileContents("local8bit");
2229 return normalize_c(file_content);
2233 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2235 docstring const tmpstr = contentsOfPlaintextFile(f);
2240 Cursor & cur = cursor();
2241 cap::replaceSelection(cur);
2242 buffer_.undo().recordUndo(cur);
2244 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2246 cur.innerText()->insertStringAsLines(cur, tmpstr);
2253 docstring const & BufferView::inlineCompletion() const
2255 return d->inlineCompletion_;
2259 size_t const & BufferView::inlineCompletionUniqueChars() const
2261 return d->inlineCompletionUniqueChars_;
2265 DocIterator const & BufferView::inlineCompletionPos() const
2267 return d->inlineCompletionPos_;
2271 bool samePar(DocIterator const & a, DocIterator const & b)
2273 if (a.empty() && b.empty())
2275 if (a.empty() || b.empty())
2277 return &a.innerParagraph() == &b.innerParagraph();
2281 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2282 docstring const & completion, size_t uniqueChars)
2284 uniqueChars = min(completion.size(), uniqueChars);
2285 bool changed = d->inlineCompletion_ != completion
2286 || d->inlineCompletionUniqueChars_ != uniqueChars;
2287 bool singlePar = true;
2288 d->inlineCompletion_ = completion;
2289 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2291 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2294 DocIterator const & old = d->inlineCompletionPos_;
2296 //lyxerr << "inlineCompletionPos changed" << std::endl;
2297 // old or pos are in another paragraph?
2298 if ((!samePar(cur, pos) && !pos.empty())
2299 || (!samePar(cur, old) && !old.empty())) {
2301 //lyxerr << "different paragraph" << std::endl;
2303 d->inlineCompletionPos_ = pos;
2308 if (singlePar && !(cur.disp_.update() & Update::Force))
2309 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2311 cur.updateFlags(cur.disp_.update() | Update::Force);