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"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "EmbeddedFiles.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 last_inset_(0), gui_(0)
221 ScrollbarParameters scrollbarParameters_;
223 ScreenUpdateStrategy update_strategy_;
225 CoordCache coord_cache_;
227 /// Estimated average par height for scrollbar.
229 /// this is used to handle XSelection events in the right manner.
238 pit_type anchor_pit_;
242 vector<int> par_height_;
245 DocIterator inlineCompletionPos;
247 docstring inlineCompletion;
249 size_t inlineCompletionUniqueChars;
251 /// keyboard mapping object.
254 /// last visited inset.
255 /** kept to send setMouseHover(false).
256 * Not owned, so don't delete.
260 mutable TextMetricsCache text_metrics_;
263 /** Not owned, so don't delete.
265 frontend::GuiBufferViewDelegate * gui_;
269 BufferView::BufferView(Buffer & buf)
270 : width_(0), height_(0), full_screen_(false), buffer_(buf), d(new Private(*this))
272 d->xsel_cache_.set = false;
273 d->intl_.initKeyMapper(lyxrc.use_kbmap);
275 d->cursor_.push(buffer_.inset());
276 d->cursor_.resetAnchor();
277 d->cursor_.setCurrentFont();
279 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
280 graphics::Previews::get().generateBufferPreviews(buffer_);
284 BufferView::~BufferView()
286 // current buffer is going to be switched-off, save cursor pos
287 // Ideally, the whole cursor stack should be saved, but session
288 // currently can only handle bottom (whole document) level pit and pos.
289 // That is to say, if a cursor is in a nested inset, it will be
290 // restore to the left of the top level inset.
291 LastFilePosSection::FilePos fp;
292 fp.pit = d->cursor_.bottom().pit();
293 fp.pos = d->cursor_.bottom().pos();
294 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
300 int BufferView::rightMargin() const
302 // The additional test for the case the outliner is opened.
304 !lyxrc.full_screen_limit ||
305 width_ < lyxrc.full_screen_width + 20)
308 return (width_ - lyxrc.full_screen_width) / 2;
312 int BufferView::leftMargin() const
314 return rightMargin();
318 bool BufferView::isTopScreen() const
320 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
324 bool BufferView::isBottomScreen() const
326 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
330 Intl & BufferView::getIntl()
336 Intl const & BufferView::getIntl() const
342 CoordCache & BufferView::coordCache()
344 return d->coord_cache_;
348 CoordCache const & BufferView::coordCache() const
350 return d->coord_cache_;
354 Buffer & BufferView::buffer()
360 Buffer const & BufferView::buffer() const
366 bool BufferView::fitCursor()
368 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
369 frontend::FontMetrics const & fm =
370 theFontMetrics(d->cursor_.getFont().fontInfo());
371 int const asc = fm.maxAscent();
372 int const des = fm.maxDescent();
373 Point const p = getPos(d->cursor_, d->cursor_.boundary());
374 if (p.y_ - asc >= 0 && p.y_ + des < height_)
381 void BufferView::processUpdateFlags(Update::flags flags)
383 // last_inset_ points to the last visited inset. This pointer may become
384 // invalid because of keyboard editing. Since all such operations
385 // causes screen update(), I reset last_inset_ to avoid such a problem.
387 // This is close to a hot-path.
388 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
389 << "[fitcursor = " << (flags & Update::FitCursor)
390 << ", forceupdate = " << (flags & Update::Force)
391 << ", singlepar = " << (flags & Update::SinglePar)
392 << "] buffer: " << &buffer_);
394 buffer_.updateMacros();
396 // Now do the first drawing step if needed. This consists on updating
397 // the CoordCache in updateMetrics().
398 // The second drawing step is done in WorkArea::redraw() if needed.
400 // Case when no explicit update is requested.
402 // no need to redraw anything.
403 d->update_strategy_ = NoScreenUpdate;
407 if (flags == Update::Decoration) {
408 d->update_strategy_ = DecorationUpdate;
413 if (flags == Update::FitCursor
414 || flags == (Update::Decoration | Update::FitCursor)) {
415 // tell the frontend to update the screen if needed.
420 if (flags & Update::Decoration) {
421 d->update_strategy_ = DecorationUpdate;
425 // no screen update is needed.
426 d->update_strategy_ = NoScreenUpdate;
430 bool const full_metrics = flags & Update::Force || !singleParUpdate();
433 // We have to update the full screen metrics.
436 if (!(flags & Update::FitCursor)) {
437 // Nothing to do anymore. Trigger a redraw and return
442 // updateMetrics() does not update paragraph position
443 // This is done at draw() time. So we need a redraw!
447 // The cursor is off screen so ensure it is visible.
454 void BufferView::updateScrollbar()
459 // We prefer fixed size line scrolling.
460 d->scrollbarParameters_.single_step = defaultRowHeight();
461 // We prefer full screen page scrolling.
462 d->scrollbarParameters_.page_step = height_;
464 Text & t = buffer_.text();
465 TextMetrics & tm = d->text_metrics_[&t];
467 LYXERR(Debug::GUI, " Updating scrollbar: height: "
468 << t.paragraphs().size()
469 << " curr par: " << d->cursor_.bottom().pit()
470 << " default height " << defaultRowHeight());
472 size_t const parsize = t.paragraphs().size();
473 if (d->par_height_.size() != parsize) {
474 d->par_height_.clear();
475 // FIXME: We assume a default paragraph height of 2 rows. This
476 // should probably be pondered with the screen width.
477 d->par_height_.resize(parsize, defaultRowHeight() * 2);
480 // Look at paragraph heights on-screen
481 pair<pit_type, ParagraphMetrics const *> first = tm.first();
482 pair<pit_type, ParagraphMetrics const *> last = tm.last();
483 for (pit_type pit = first.first; pit <= last.first; ++pit) {
484 d->par_height_[pit] = tm.parMetrics(pit).height();
485 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
486 << d->par_height_[pit]);
489 int top_pos = first.second->position() - first.second->ascent();
490 int bottom_pos = last.second->position() + last.second->descent();
491 bool first_visible = first.first == 0 && top_pos >= 0;
492 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
493 if (first_visible && last_visible) {
494 d->scrollbarParameters_.min = 0;
495 d->scrollbarParameters_.max = 0;
499 d->scrollbarParameters_.min = top_pos;
500 for (size_t i = 0; i != size_t(first.first); ++i)
501 d->scrollbarParameters_.min -= d->par_height_[i];
502 d->scrollbarParameters_.max = bottom_pos;
503 for (size_t i = last.first + 1; i != parsize; ++i)
504 d->scrollbarParameters_.max += d->par_height_[i];
506 d->scrollbarParameters_.position = 0;
507 // The reference is the top position so we remove one page.
508 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
512 ScrollbarParameters const & BufferView::scrollbarParameters() const
514 return d->scrollbarParameters_;
518 docstring BufferView::toolTip(int x, int y) const
520 // Get inset under mouse, if there is one.
521 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
523 // No inset, no tooltip...
525 return covering_inset->toolTip(*this, x, y);
529 docstring BufferView::contextMenu(int x, int y) const
531 // Get inset under mouse, if there is one.
532 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
534 return covering_inset->contextMenu(*this, x, y);
536 return buffer_.inset().contextMenu(*this, x, y);
540 void BufferView::scrollDocView(int value)
542 int const offset = value - d->scrollbarParameters_.position;
543 // If the offset is less than 2 screen height, prefer to scroll instead.
544 if (abs(offset) <= 2 * height_) {
549 // cut off at the top
550 if (value <= d->scrollbarParameters_.min) {
551 DocIterator dit = doc_iterator_begin(buffer_.inset());
553 LYXERR(Debug::SCROLLING, "scroll to top");
557 // cut off at the bottom
558 if (value >= d->scrollbarParameters_.max) {
559 DocIterator dit = doc_iterator_end(buffer_.inset());
562 LYXERR(Debug::SCROLLING, "scroll to bottom");
566 // find paragraph at target position
567 int par_pos = d->scrollbarParameters_.min;
569 for (; i != int(d->par_height_.size()); ++i) {
570 par_pos += d->par_height_[i];
571 if (par_pos >= value)
575 if (par_pos < value) {
576 // It seems we didn't find the correct pit so stay on the safe side and
578 LYXERR0("scrolling position not found!");
579 scrollDocView(d->scrollbarParameters_.max);
583 DocIterator dit = doc_iterator_begin(buffer_.inset());
585 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
590 // FIXME: this method is not working well.
591 void BufferView::setCursorFromScrollbar()
593 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
595 int const height = 2 * defaultRowHeight();
596 int const first = height;
597 int const last = height_ - height;
598 Cursor & cur = d->cursor_;
600 switch (cursorStatus(cur)) {
602 // We reset the cursor because cursorStatus() does not
603 // work when the cursor is within mathed.
604 cur.reset(buffer_.inset());
605 tm.setCursorFromCoordinates(cur, 0, first);
606 cur.clearSelection();
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, last);
613 cur.clearSelection();
616 int const y = getPos(cur, cur.boundary()).y_;
617 int const newy = min(last, max(y, first));
619 cur.reset(buffer_.inset());
620 tm.setCursorFromCoordinates(cur, 0, newy);
626 Change const BufferView::getCurrentChange() const
628 if (!d->cursor_.selection())
629 return Change(Change::UNCHANGED);
631 DocIterator dit = d->cursor_.selectionBegin();
632 return dit.paragraph().lookupChange(dit.pos());
636 // this could be used elsewhere as well?
637 // FIXME: This does not work within mathed!
638 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
640 Point const p = getPos(dit, dit.boundary());
643 if (p.y_ > workHeight())
649 void BufferView::saveBookmark(unsigned int idx)
651 // tenatively save bookmark, id and pos will be used to
652 // acturately locate a bookmark in a 'live' lyx session.
653 // pit and pos will be updated with bottom level pit/pos
655 LyX::ref().session().bookmarks().save(
657 d->cursor_.bottom().pit(),
658 d->cursor_.bottom().pos(),
659 d->cursor_.paragraph().id(),
664 // emit message signal.
665 message(_("Save bookmark"));
669 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
670 int top_id, pos_type top_pos)
672 bool success = false;
675 d->cursor_.clearSelection();
677 // if a valid par_id is given, try it first
678 // This is the case for a 'live' bookmark when unique paragraph ID
679 // is used to track bookmarks.
681 dit = buffer_.getParFromID(top_id);
683 dit.pos() = min(dit.paragraph().size(), top_pos);
684 // Some slices of the iterator may not be
685 // reachable (e.g. closed collapsable inset)
686 // so the dociterator may need to be
687 // shortened. Otherwise, setCursor may crash
688 // lyx when the cursor can not be set to these
690 size_t const n = dit.depth();
691 for (size_t i = 0; i < n; ++i)
692 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
700 // if top_id == 0, or searching through top_id failed
701 // This is the case for a 'restored' bookmark when only bottom
702 // (document level) pit was saved. Because of this, bookmark
703 // restoration is inaccurate. If a bookmark was within an inset,
704 // it will be restored to the left of the outmost inset that contains
706 if (bottom_pit < int(buffer_.paragraphs().size())) {
707 dit = doc_iterator_begin(buffer_.inset());
709 dit.pit() = bottom_pit;
710 dit.pos() = min(bottom_pos, dit.paragraph().size());
715 // Note: only bottom (document) level pit is set.
717 // set the current font.
718 d->cursor_.setCurrentFont();
719 // To center the screen on this new position we need the
720 // paragraph position which is computed at draw() time.
721 // So we need a redraw!
731 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
733 if (lyxrc.rtl_support) {
734 if (d->cursor_.real_current_font.isRightToLeft()) {
735 if (d->intl_.keymap == Intl::PRIMARY)
736 d->intl_.keyMapSec();
738 if (d->intl_.keymap == Intl::SECONDARY)
739 d->intl_.keyMapPrim();
743 d->intl_.getTransManager().translateAndInsert(c, t, cur);
747 int BufferView::workWidth() const
753 void BufferView::showCursor()
755 showCursor(d->cursor_);
759 void BufferView::showCursor(DocIterator const & dit)
761 // We are not properly started yet, delay until resizing is
766 LYXERR(Debug::SCROLLING, "recentering!");
768 CursorSlice const & bot = dit.bottom();
769 TextMetrics & tm = d->text_metrics_[bot.text()];
771 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
772 int bot_pit = bot.pit();
773 if (bot_pit > max_pit) {
774 // FIXME: Why does this happen?
775 LYXERR0("bottom pit is greater that max pit: "
776 << bot_pit << " > " << max_pit);
780 if (bot_pit == tm.first().first - 1)
781 tm.newParMetricsUp();
782 else if (bot_pit == tm.last().first + 1)
783 tm.newParMetricsDown();
785 if (tm.contains(bot_pit)) {
786 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
787 BOOST_ASSERT(!pm.rows().empty());
788 // FIXME: smooth scrolling doesn't work in mathed.
789 CursorSlice const & cs = dit.innerTextSlice();
790 int offset = coordOffset(dit, dit.boundary()).y_;
791 int ypos = pm.position() + offset;
792 Dimension const & row_dim =
793 pm.getRow(cs.pos(), dit.boundary()).dimension();
794 if (ypos - row_dim.ascent() < 0)
795 scrollUp(- ypos + row_dim.ascent());
796 else if (ypos + row_dim.descent() > height_)
797 scrollDown(ypos - height_ + row_dim.descent());
798 // else, nothing to do, the cursor is already visible so we just return.
802 // fix inline completion position
803 if (d->inlineCompletionPos.fixIfBroken())
804 d->inlineCompletionPos = DocIterator();
806 tm.redoParagraph(bot_pit);
807 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
808 int offset = coordOffset(dit, dit.boundary()).y_;
810 d->anchor_pit_ = bot_pit;
811 CursorSlice const & cs = dit.innerTextSlice();
812 Dimension const & row_dim =
813 pm.getRow(cs.pos(), dit.boundary()).dimension();
815 if (d->anchor_pit_ == 0)
816 d->anchor_ypos_ = offset + pm.ascent();
817 else if (d->anchor_pit_ == max_pit)
818 d->anchor_ypos_ = height_ - offset - row_dim.descent();
820 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
827 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
831 Cursor & cur = d->cursor_;
833 switch (cmd.action) {
836 flag.enabled(buffer_.undo().hasUndoStack());
839 flag.enabled(buffer_.undo().hasRedoStack());
841 case LFUN_FILE_INSERT:
842 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
843 case LFUN_FILE_INSERT_PLAINTEXT:
844 case LFUN_BOOKMARK_SAVE:
845 // FIXME: Actually, these LFUNS should be moved to Text
846 flag.enabled(cur.inTexted());
848 case LFUN_FONT_STATE:
849 case LFUN_LABEL_INSERT:
850 case LFUN_INFO_INSERT:
851 case LFUN_EXTERNAL_EDIT:
852 case LFUN_GRAPHICS_EDIT:
853 case LFUN_PARAGRAPH_GOTO:
855 case LFUN_REFERENCE_NEXT:
857 case LFUN_WORD_REPLACE:
860 case LFUN_MARK_TOGGLE:
861 case LFUN_SCREEN_RECENTER:
862 case LFUN_BIBTEX_DATABASE_ADD:
863 case LFUN_BIBTEX_DATABASE_DEL:
864 case LFUN_STATISTICS:
865 case LFUN_NEXT_INSET_TOGGLE:
869 case LFUN_LABEL_GOTO: {
870 flag.enabled(!cmd.argument().empty()
871 || getInsetByCode<InsetRef>(cur, REF_CODE));
875 case LFUN_CHANGES_TRACK:
877 flag.setOnOff(buffer_.params().trackChanges);
880 case LFUN_CHANGES_OUTPUT:
882 flag.setOnOff(buffer_.params().outputChanges);
885 case LFUN_CHANGES_MERGE:
886 case LFUN_CHANGE_NEXT:
887 case LFUN_ALL_CHANGES_ACCEPT:
888 case LFUN_ALL_CHANGES_REJECT:
889 // TODO: context-sensitive enabling of LFUNs
890 // In principle, these command should only be enabled if there
891 // is a change in the document. However, without proper
892 // optimizations, this will inevitably result in poor performance.
896 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
897 flag.setOnOff(buffer_.params().compressed);
901 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
902 flag.setOnOff(buffer_.params().embedded);
907 case LFUN_SCREEN_DOWN:
909 case LFUN_SCREEN_UP_SELECT:
910 case LFUN_SCREEN_DOWN_SELECT:
914 case LFUN_LAYOUT_TABULAR:
915 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
919 flag.enabled(!cur.inset().forceEmptyLayout(cur.idx()));
922 case LFUN_LAYOUT_PARAGRAPH:
923 flag.enabled(cur.inset().allowParagraphCustomization(cur.idx()));
926 case LFUN_INSET_SETTINGS: {
927 InsetCode code = cur.inset().lyxCode();
931 enable = cmd.argument() == "tabular";
934 enable = cmd.argument() == "ert";
937 enable = cmd.argument() == "float";
940 enable = cmd.argument() == "wrap";
943 enable = cmd.argument() == "note";
946 enable = cmd.argument() == "branch";
949 enable = cmd.argument() == "box";
952 enable = cmd.argument() == "listings";
957 flag.enabled(enable);
961 case LFUN_DIALOG_SHOW_NEW_INSET:
962 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
963 cur.inset().lyxCode() != LISTINGS_CODE);
964 if (cur.inset().lyxCode() == CAPTION_CODE) {
966 if (cur.inset().getStatus(cur, cmd, flag))
979 bool BufferView::dispatch(FuncRequest const & cmd)
981 //lyxerr << [ cmd = " << cmd << "]" << endl;
983 // Make sure that the cached BufferView is correct.
984 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
985 << " arg[" << to_utf8(cmd.argument()) << ']'
986 << " x[" << cmd.x << ']'
987 << " y[" << cmd.y << ']'
988 << " button[" << cmd.button() << ']');
990 Cursor & cur = d->cursor_;
992 switch (cmd.action) {
995 cur.message(_("Undo"));
996 cur.clearSelection();
998 cur.message(_("No further undo information"));
1000 processUpdateFlags(Update::Force | Update::FitCursor);
1004 cur.message(_("Redo"));
1005 cur.clearSelection();
1006 if (!cur.textRedo())
1007 cur.message(_("No further redo information"));
1009 processUpdateFlags(Update::Force | Update::FitCursor);
1012 case LFUN_FONT_STATE:
1013 cur.message(cur.currentState());
1016 case LFUN_BOOKMARK_SAVE:
1017 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1020 case LFUN_LABEL_GOTO: {
1021 docstring label = cmd.argument();
1022 if (label.empty()) {
1024 getInsetByCode<InsetRef>(d->cursor_,
1027 label = inset->getParam("reference");
1028 // persistent=false: use temp_bookmark
1038 case LFUN_EXTERNAL_EDIT: {
1039 FuncRequest fr(cmd);
1040 InsetExternal * inset = getInsetByCode<InsetExternal>(d->cursor_,
1043 inset->dispatch(d->cursor_, fr);
1048 case LFUN_GRAPHICS_EDIT: {
1049 FuncRequest fr(cmd);
1050 InsetGraphics * inset = getInsetByCode<InsetGraphics>(d->cursor_,
1053 inset->dispatch(d->cursor_, fr);
1057 case LFUN_PARAGRAPH_GOTO: {
1058 int const id = convert<int>(to_utf8(cmd.argument()));
1060 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1061 b = theBufferList().next(b)) {
1063 DocIterator dit = b->getParFromID(id);
1065 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1069 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1070 << " found in buffer `"
1071 << b->absFileName() << "'.");
1073 if (b == &buffer_) {
1076 processUpdateFlags(Update::Force | Update::FitCursor);
1078 // Switch to other buffer view and resend cmd
1079 theLyXFunc().dispatch(FuncRequest(
1080 LFUN_BUFFER_SWITCH, b->absFileName()));
1081 theLyXFunc().dispatch(cmd);
1088 case LFUN_NOTE_NEXT:
1089 gotoInset(this, NOTE_CODE, false);
1092 case LFUN_REFERENCE_NEXT: {
1093 vector<InsetCode> tmp;
1094 tmp.push_back(LABEL_CODE);
1095 tmp.push_back(REF_CODE);
1096 gotoInset(this, tmp, true);
1100 case LFUN_CHANGES_TRACK:
1101 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1104 case LFUN_CHANGES_OUTPUT:
1105 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1106 if (buffer_.params().outputChanges) {
1107 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1108 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1109 LaTeXFeatures::isAvailable("xcolor");
1111 if (!dvipost && !xcolorsoul) {
1112 Alert::warning(_("Changes not shown in LaTeX output"),
1113 _("Changes will not be highlighted in LaTeX output, "
1114 "because neither dvipost nor xcolor/soul are installed.\n"
1115 "Please install these packages or redefine "
1116 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1117 } else if (!xcolorsoul) {
1118 Alert::warning(_("Changes not shown in LaTeX output"),
1119 _("Changes will not be highlighted in LaTeX output "
1120 "when using pdflatex, because xcolor and soul are not installed.\n"
1121 "Please install both packages or redefine "
1122 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1127 case LFUN_CHANGE_NEXT:
1128 findNextChange(this);
1131 case LFUN_CHANGES_MERGE:
1132 if (findNextChange(this))
1133 showDialog("changes");
1136 case LFUN_ALL_CHANGES_ACCEPT:
1137 // select complete document
1138 d->cursor_.reset(buffer_.inset());
1139 d->cursor_.selHandle(true);
1140 buffer_.text().cursorBottom(d->cursor_);
1141 // accept everything in a single step to support atomic undo
1142 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1145 case LFUN_ALL_CHANGES_REJECT:
1146 // select complete document
1147 d->cursor_.reset(buffer_.inset());
1148 d->cursor_.selHandle(true);
1149 buffer_.text().cursorBottom(d->cursor_);
1150 // reject everything in a single step to support atomic undo
1151 // Note: reject does not work recursively; the user may have to repeat the operation
1152 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1155 case LFUN_WORD_FIND:
1156 if (find(this, cmd))
1159 message(_("String not found!"));
1162 case LFUN_WORD_REPLACE: {
1163 bool has_deleted = false;
1164 if (cur.selection()) {
1165 DocIterator beg = cur.selectionBegin();
1166 DocIterator end = cur.selectionEnd();
1167 if (beg.pit() == end.pit()) {
1168 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1169 if (cur.paragraph().isDeleted(p))
1174 replace(this, cmd, has_deleted);
1179 cur.clearSelection();
1181 cur.message(from_utf8(N_("Mark off")));
1185 cur.clearSelection();
1188 cur.message(from_utf8(N_("Mark on")));
1191 case LFUN_MARK_TOGGLE:
1192 cur.clearSelection();
1195 cur.message(from_utf8(N_("Mark removed")));
1198 cur.message(from_utf8(N_("Mark set")));
1203 case LFUN_SCREEN_RECENTER:
1207 case LFUN_BIBTEX_DATABASE_ADD: {
1208 Cursor tmpcur = d->cursor_;
1209 findInset(tmpcur, BIBTEX_CODE, false);
1210 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1213 if (inset->addDatabase(to_utf8(cmd.argument())))
1214 buffer_.updateBibfilesCache();
1219 case LFUN_BIBTEX_DATABASE_DEL: {
1220 Cursor tmpcur = d->cursor_;
1221 findInset(tmpcur, BIBTEX_CODE, false);
1222 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1225 if (inset->delDatabase(to_utf8(cmd.argument())))
1226 buffer_.updateBibfilesCache();
1231 case LFUN_STATISTICS: {
1232 DocIterator from, to;
1233 if (cur.selection()) {
1234 from = cur.selectionBegin();
1235 to = cur.selectionEnd();
1237 from = doc_iterator_begin(buffer_.inset());
1238 to = doc_iterator_end(buffer_.inset());
1240 int const words = countWords(from, to);
1241 int const chars = countChars(from, to, false);
1242 int const chars_blanks = countChars(from, to, true);
1244 if (cur.selection())
1245 message = _("Statistics for the selection:");
1247 message = _("Statistics for the document:");
1250 message += bformat(_("%1$d words"), words);
1252 message += _("One word");
1254 if (chars_blanks != 1)
1255 message += bformat(_("%1$d characters (including blanks)"),
1258 message += _("One character (including blanks)");
1261 message += bformat(_("%1$d characters (excluding blanks)"),
1264 message += _("One character (excluding blanks)");
1266 Alert::information(_("Statistics"), message);
1270 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1271 // turn compression on/off
1272 buffer_.params().compressed = !buffer_.params().compressed;
1275 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
1276 // turn embedding on/off
1278 buffer_.embeddedFiles().enable(!buffer_.params().embedded, buffer_, true);
1279 } catch (ExceptionMessage const & message) {
1280 Alert::error(message.title_, message.details_);
1285 case LFUN_NEXT_INSET_TOGGLE: {
1286 // this is the real function we want to invoke
1287 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1288 // if there is an inset at cursor, see whether it
1290 Inset * inset = cur.nextInset();
1292 if (inset->isActive()) {
1293 Cursor tmpcur = cur;
1294 tmpcur.pushBackward(*inset);
1295 inset->dispatch(tmpcur, tmpcmd);
1296 if (tmpcur.result().dispatched()) {
1299 } else if (inset->editable() == Inset::IS_EDITABLE) {
1300 inset->edit(cur, true);
1303 // if it did not work, try the underlying inset.
1304 if (!cur.result().dispatched())
1305 cur.dispatch(tmpcmd);
1307 if (!cur.result().dispatched())
1308 // It did not work too; no action needed.
1310 cur.clearSelection();
1311 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1315 case LFUN_SCREEN_UP:
1316 case LFUN_SCREEN_DOWN: {
1317 Point p = getPos(cur, cur.boundary());
1318 if (p.y_ < 0 || p.y_ > height_) {
1319 // The cursor is off-screen so recenter before proceeding.
1321 p = getPos(cur, cur.boundary());
1323 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1324 cur.reset(buffer_.inset());
1325 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1326 //FIXME: what to do with cur.x_target()?
1335 case LFUN_SCREEN_UP_SELECT: {
1336 cur.selHandle(true);
1337 if (isTopScreen()) {
1338 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1342 int y = getPos(cur, cur.boundary()).y_;
1343 int const ymin = y - height_ + defaultRowHeight();
1344 while (y > ymin && cur.up())
1345 y = getPos(cur, cur.boundary()).y_;
1348 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1352 case LFUN_SCREEN_DOWN_SELECT: {
1353 cur.selHandle(true);
1354 if (isBottomScreen()) {
1355 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1359 int y = getPos(cur, cur.boundary()).y_;
1360 int const ymax = y + height_ - defaultRowHeight();
1361 while (y < ymax && cur.down())
1362 y = getPos(cur, cur.boundary()).y_;
1365 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1377 docstring const BufferView::requestSelection()
1379 Cursor & cur = d->cursor_;
1381 if (!cur.selection()) {
1382 d->xsel_cache_.set = false;
1386 if (!d->xsel_cache_.set ||
1387 cur.top() != d->xsel_cache_.cursor ||
1388 cur.anchor_.top() != d->xsel_cache_.anchor)
1390 d->xsel_cache_.cursor = cur.top();
1391 d->xsel_cache_.anchor = cur.anchor_.top();
1392 d->xsel_cache_.set = cur.selection();
1393 return cur.selectionAsString(false);
1399 void BufferView::clearSelection()
1401 d->cursor_.clearSelection();
1402 // Clear the selection buffer. Otherwise a subsequent
1403 // middle-mouse-button paste would use the selection buffer,
1404 // not the more current external selection.
1405 cap::clearSelection();
1406 d->xsel_cache_.set = false;
1407 // The buffer did not really change, but this causes the
1408 // redraw we need because we cleared the selection above.
1413 void BufferView::resize(int width, int height)
1415 // Update from work area
1419 // Clear the paragraph height cache.
1420 d->par_height_.clear();
1421 // Redo the metrics.
1426 Inset const * BufferView::getCoveringInset(Text const & text,
1429 TextMetrics & tm = d->text_metrics_[&text];
1430 Inset * inset = tm.checkInsetHit(x, y);
1434 if (!inset->descendable())
1435 // No need to go further down if the inset is not
1439 size_t cell_number = inset->nargs();
1440 // Check all the inner cell.
1441 for (size_t i = 0; i != cell_number; ++i) {
1442 Text const * inner_text = inset->getText(i);
1445 Inset const * inset_deeper =
1446 getCoveringInset(*inner_text, x, y);
1448 return inset_deeper;
1456 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1458 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1460 // This is only called for mouse related events including
1461 // LFUN_FILE_OPEN generated by drag-and-drop.
1462 FuncRequest cmd = cmd0;
1464 Cursor old = cursor();
1466 cur.push(buffer_.inset());
1467 cur.selection() = d->cursor_.selection();
1469 // Either the inset under the cursor or the
1470 // surrounding Text will handle this event.
1472 // make sure we stay within the screen...
1473 cmd.y = min(max(cmd.y, -1), height_);
1475 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1477 // Get inset under mouse, if there is one.
1478 Inset const * covering_inset =
1479 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1480 if (covering_inset == d->last_inset_)
1481 // Same inset, no need to do anything...
1484 bool need_redraw = false;
1485 // const_cast because of setMouseHover().
1486 Inset * inset = const_cast<Inset *>(covering_inset);
1488 // Remove the hint on the last hovered inset (if any).
1489 need_redraw |= d->last_inset_->setMouseHover(false);
1491 // Highlighted the newly hovered inset (if any).
1492 need_redraw |= inset->setMouseHover(true);
1493 d->last_inset_ = inset;
1497 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1498 << cmd.x << ", " << cmd.y << ")");
1500 d->update_strategy_ = DecorationUpdate;
1502 // This event (moving without mouse click) is not passed further.
1503 // This should be changed if it is further utilized.
1508 // Build temporary cursor.
1509 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1511 // Put anchor at the same position.
1514 // Try to dispatch to an non-editable inset near this position
1515 // via the temp cursor. If the inset wishes to change the real
1516 // cursor it has to do so explicitly by using
1517 // cur.bv().cursor() = cur; (or similar)
1519 inset->dispatch(cur, cmd);
1521 // Now dispatch to the temporary cursor. If the real cursor should
1522 // be modified, the inset's dispatch has to do so explicitly.
1523 if (!cur.result().dispatched())
1526 // Notify left insets
1529 bool badcursor = notifyCursorLeaves(old, cur);
1531 cursor().fixIfBroken();
1534 // Do we have a selection?
1535 theSelection().haveSelection(cursor().selection());
1537 // If the command has been dispatched,
1538 if (cur.result().dispatched() || cur.result().update())
1539 processUpdateFlags(cur.result().update());
1543 void BufferView::lfunScroll(FuncRequest const & cmd)
1545 string const scroll_type = cmd.getArg(0);
1546 int const scroll_step =
1547 (scroll_type == "line")? d->scrollbarParameters_.single_step
1548 : (scroll_type == "page")? d->scrollbarParameters_.page_step : 0;
1549 if (scroll_step == 0)
1551 string const scroll_quantity = cmd.getArg(1);
1552 if (scroll_quantity == "up")
1553 scrollUp(scroll_step);
1554 else if (scroll_quantity == "down")
1555 scrollDown(scroll_step);
1557 int const scroll_value = convert<int>(scroll_quantity);
1559 scroll(scroll_step * scroll_value);
1564 void BufferView::scroll(int y)
1573 void BufferView::scrollDown(int offset)
1575 Text * text = &buffer_.text();
1576 TextMetrics & tm = d->text_metrics_[text];
1577 int ymax = height_ + offset;
1579 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1580 int bottom_pos = last.second->position() + last.second->descent();
1581 if (last.first + 1 == int(text->paragraphs().size())) {
1582 if (bottom_pos <= height_)
1584 offset = min(offset, bottom_pos - height_);
1587 if (bottom_pos > ymax)
1589 tm.newParMetricsDown();
1591 d->anchor_ypos_ -= offset;
1597 void BufferView::scrollUp(int offset)
1599 Text * text = &buffer_.text();
1600 TextMetrics & tm = d->text_metrics_[text];
1601 int ymin = - offset;
1603 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1604 int top_pos = first.second->position() - first.second->ascent();
1605 if (first.first == 0) {
1608 offset = min(offset, - top_pos);
1613 tm.newParMetricsUp();
1615 d->anchor_ypos_ += offset;
1621 void BufferView::setCursorFromRow(int row)
1626 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1628 d->cursor_.reset(buffer_.inset());
1630 buffer_.text().setCursor(d->cursor_, 0, 0);
1632 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1636 void BufferView::gotoLabel(docstring const & label)
1638 Toc & toc = buffer().tocBackend().toc("label");
1639 TocIterator toc_it = toc.begin();
1640 TocIterator end = toc.end();
1641 for (; toc_it != end; ++toc_it) {
1642 if (label == toc_it->str())
1643 dispatch(toc_it->action());
1645 //FIXME: We could do a bit more searching thanks to this:
1646 //InsetLabel const * inset = buffer_.insetLabel(label);
1650 TextMetrics const & BufferView::textMetrics(Text const * t) const
1652 return const_cast<BufferView *>(this)->textMetrics(t);
1656 TextMetrics & BufferView::textMetrics(Text const * t)
1658 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1659 if (tmc_it == d->text_metrics_.end()) {
1660 tmc_it = d->text_metrics_.insert(
1661 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1663 return tmc_it->second;
1667 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1670 return textMetrics(t).parMetrics(pit);
1674 int BufferView::workHeight() const
1680 void BufferView::setCursor(DocIterator const & dit)
1682 size_t const n = dit.depth();
1683 for (size_t i = 0; i < n; ++i)
1684 dit[i].inset().edit(d->cursor_, true);
1686 d->cursor_.setCursor(dit);
1687 d->cursor_.selection() = false;
1691 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1693 // Would be wrong to delete anything if we have a selection.
1694 if (cur.selection())
1697 bool need_anchor_change = false;
1698 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1699 need_anchor_change);
1701 if (need_anchor_change)
1709 updateLabels(buffer_);
1717 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1719 BOOST_ASSERT(&cur.bv() == this);
1722 // this event will clear selection so we save selection for
1723 // persistent selection
1724 cap::saveSelection(cursor());
1726 // Has the cursor just left the inset?
1727 bool badcursor = false;
1728 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1730 d->cursor_.fixIfBroken();
1731 badcursor = notifyCursorLeaves(d->cursor_, cur);
1736 // FIXME: shift-mouse selection doesn't work well across insets.
1737 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1739 // do the dEPM magic if needed
1740 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1741 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1742 // the leftinset bool would not be necessary (badcursor instead).
1743 bool update = leftinset;
1744 if (!do_selection && !badcursor && d->cursor_.inTexted())
1745 update |= checkDepm(cur, d->cursor_);
1747 d->cursor_.setCursor(cur);
1748 d->cursor_.boundary(cur.boundary());
1750 d->cursor_.setSelection();
1752 d->cursor_.clearSelection();
1754 d->cursor_.finishUndo();
1755 d->cursor_.setCurrentFont();
1760 void BufferView::putSelectionAt(DocIterator const & cur,
1761 int length, bool backwards)
1763 d->cursor_.clearSelection();
1769 d->cursor_.pos() += length;
1770 d->cursor_.setSelection(d->cursor_, -length);
1772 d->cursor_.setSelection(d->cursor_, length);
1774 // Ensure a redraw happens in any case because the new selection could
1775 // possibly be on the same screen as the previous selection.
1776 processUpdateFlags(Update::Force | Update::FitCursor);
1780 Cursor & BufferView::cursor()
1786 Cursor const & BufferView::cursor() const
1792 pit_type BufferView::anchor_ref() const
1794 return d->anchor_pit_;
1798 bool BufferView::singleParUpdate()
1800 Text & buftext = buffer_.text();
1801 pit_type const bottom_pit = d->cursor_.bottom().pit();
1802 TextMetrics & tm = textMetrics(&buftext);
1803 int old_height = tm.parMetrics(bottom_pit).height();
1805 // make sure inline completion pointer is ok
1806 if (d->inlineCompletionPos.fixIfBroken())
1807 d->inlineCompletionPos = DocIterator();
1809 // In Single Paragraph mode, rebreak only
1810 // the (main text, not inset!) paragraph containing the cursor.
1811 // (if this paragraph contains insets etc., rebreaking will
1812 // recursively descend)
1813 tm.redoParagraph(bottom_pit);
1814 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1815 if (pm.height() != old_height)
1816 // Paragraph height has changed so we cannot proceed to
1817 // the singlePar optimisation.
1820 d->update_strategy_ = SingleParUpdate;
1822 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1823 << " y2: " << pm.position() + pm.descent()
1824 << " pit: " << bottom_pit
1825 << " singlepar: 1");
1830 void BufferView::updateMetrics()
1832 Text & buftext = buffer_.text();
1833 pit_type const npit = int(buftext.paragraphs().size());
1835 // Clear out the position cache in case of full screen redraw,
1836 d->coord_cache_.clear();
1838 // Clear out paragraph metrics to avoid having invalid metrics
1839 // in the cache from paragraphs not relayouted below
1840 // The complete text metrics will be redone.
1841 d->text_metrics_.clear();
1843 TextMetrics & tm = textMetrics(&buftext);
1845 // make sure inline completion pointer is ok
1846 if (d->inlineCompletionPos.fixIfBroken())
1847 d->inlineCompletionPos = DocIterator();
1849 if (d->anchor_pit_ >= npit)
1850 // The anchor pit must have been deleted...
1851 d->anchor_pit_ = npit - 1;
1853 // Rebreak anchor paragraph.
1854 tm.redoParagraph(d->anchor_pit_);
1855 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1858 if (d->anchor_pit_ == 0) {
1859 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
1861 // Complete buffer visible? Then it's easy.
1862 if (scrollRange == 0)
1863 d->anchor_ypos_ = anchor_pm.ascent();
1865 // FIXME: Some clever handling needed to show
1866 // the _first_ paragraph up to the top if the cursor is
1867 // in the first line.
1869 anchor_pm.setPosition(d->anchor_ypos_);
1871 LYXERR(Debug::PAINTING, "metrics: "
1872 << " anchor pit = " << d->anchor_pit_
1873 << " anchor ypos = " << d->anchor_ypos_);
1875 // Redo paragraphs above anchor if necessary.
1876 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1877 // We are now just above the anchor paragraph.
1878 pit_type pit1 = d->anchor_pit_ - 1;
1879 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1880 tm.redoParagraph(pit1);
1881 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1883 // Save the paragraph position in the cache.
1888 // Redo paragraphs below the anchor if necessary.
1889 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1890 // We are now just below the anchor paragraph.
1891 pit_type pit2 = d->anchor_pit_ + 1;
1892 for (; pit2 < npit && y2 <= height_; ++pit2) {
1893 tm.redoParagraph(pit2);
1894 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1896 // Save the paragraph position in the cache.
1901 LYXERR(Debug::PAINTING, "Metrics: "
1902 << " anchor pit = " << d->anchor_pit_
1903 << " anchor ypos = " << d->anchor_ypos_
1906 << " pit1 = " << pit1
1907 << " pit2 = " << pit2);
1909 d->update_strategy_ = FullScreenUpdate;
1911 if (lyxerr.debugging(Debug::WORKAREA)) {
1912 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1913 d->coord_cache_.dump();
1918 void BufferView::insertLyXFile(FileName const & fname)
1920 BOOST_ASSERT(d->cursor_.inTexted());
1922 // Get absolute path of file and add ".lyx"
1923 // to the filename if necessary
1924 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1926 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1927 // emit message signal.
1928 message(bformat(_("Inserting document %1$s..."), disp_fn));
1931 Buffer buf("", false);
1932 if (buf.loadLyXFile(filename)) {
1933 ErrorList & el = buffer_.errorList("Parse");
1934 // Copy the inserted document error list into the current buffer one.
1935 el = buf.errorList("Parse");
1936 buffer_.undo().recordUndo(d->cursor_);
1937 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1938 buf.params().documentClassPtr(), el);
1939 res = _("Document %1$s inserted.");
1941 res = _("Could not insert document %1$s");
1946 // emit message signal.
1947 message(bformat(res, disp_fn));
1948 buffer_.errors("Parse");
1952 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1958 // Addup contribution of nested insets, from inside to outside,
1959 // keeping the outer paragraph for a special handling below
1960 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1961 CursorSlice const & sl = dit[i];
1965 // get relative position inside sl.inset()
1966 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1968 // Make relative position inside of the edited inset relative to sl.inset()
1972 // In case of an RTL inset, the edited inset will be positioned to the left
1975 bool boundary_i = boundary && i + 1 == dit.depth();
1976 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1981 // remember width for the case that sl.inset() is positioned in an RTL inset
1982 if (i && dit[i - 1].text()) {
1983 // If this Inset is inside a Text Inset, retrieve the Dimension
1984 // from the containing text instead of using Inset::dimension() which
1985 // might not be implemented.
1986 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1987 // elimination of Inset::dim_ cache. This coordOffset() method needs
1988 // to be rewritten in light of the new design.
1989 Dimension const & dim = parMetrics(dit[i - 1].text(),
1990 dit[i - 1].pit()).insetDimension(&sl.inset());
1993 Dimension const dim = sl.inset().dimension(*this);
1997 //lyxerr << "Cursor::getPos, i: "
1998 // << i << " x: " << xx << " y: " << y << endl;
2001 // Add contribution of initial rows of outermost paragraph
2002 CursorSlice const & sl = dit[0];
2003 TextMetrics const & tm = textMetrics(sl.text());
2004 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2005 BOOST_ASSERT(!pm.rows().empty());
2006 y -= pm.rows()[0].ascent();
2008 // FIXME: document this mess
2010 if (sl.pos() > 0 && dit.depth() == 1) {
2012 if (pos && boundary)
2014 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2015 rend = pm.pos2row(pos);
2017 rend = pm.pos2row(sl.pos());
2019 size_t rend = pm.pos2row(sl.pos());
2021 for (size_t rit = 0; rit != rend; ++rit)
2022 y += pm.rows()[rit].height();
2023 y += pm.rows()[rend].ascent();
2025 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2027 // Make relative position from the nested inset now bufferview absolute.
2028 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2031 // In the RTL case place the nested inset at the left of the cursor in
2032 // the outer paragraph
2033 bool boundary_1 = boundary && 1 == dit.depth();
2034 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2042 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2044 CursorSlice const & bot = dit.bottom();
2045 TextMetrics const & tm = textMetrics(bot.text());
2046 if (!tm.contains(bot.pit()))
2047 return Point(-1, -1);
2049 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2050 p.y_ += tm.parMetrics(bot.pit()).position();
2055 void BufferView::draw(frontend::Painter & pain)
2057 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2058 Text & text = buffer_.text();
2059 TextMetrics const & tm = d->text_metrics_[&text];
2060 int const y = tm.first().second->position();
2061 PainterInfo pi(this, pain);
2063 switch (d->update_strategy_) {
2065 case NoScreenUpdate:
2066 // If no screen painting is actually needed, only some the different
2067 // coordinates of insets and paragraphs needs to be updated.
2068 pi.full_repaint = true;
2069 pi.pain.setDrawingEnabled(false);
2073 case SingleParUpdate:
2074 pi.full_repaint = false;
2075 // In general, only the current row of the outermost paragraph
2076 // will be redrawn. Particular cases where selection spans
2077 // multiple paragraph are correctly detected in TextMetrics.
2081 case DecorationUpdate:
2082 // FIXME: We should also distinguish DecorationUpdate to avoid text
2083 // drawing if possible. This is not possible to do easily right now
2084 // because of the single backing pixmap.
2086 case FullScreenUpdate:
2087 // The whole screen, including insets, will be refreshed.
2088 pi.full_repaint = true;
2090 // Clear background.
2091 pain.fillRectangle(0, 0, width_, height_,
2092 buffer_.inset().backgroundColor());
2097 // and possibly grey out below
2098 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2099 int const y2 = lastpm.second->position() + lastpm.second->descent();
2101 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2104 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2106 // The scrollbar needs an update.
2109 // Normalize anchor for next time
2110 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2111 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2112 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2113 ParagraphMetrics const & pm = tm.parMetrics(pit);
2114 if (pm.position() + pm.descent() > 0) {
2115 d->anchor_pit_ = pit;
2116 d->anchor_ypos_ = pm.position();
2120 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2121 << " anchor ypos = " << d->anchor_ypos_);
2125 void BufferView::message(docstring const & msg)
2128 d->gui_->message(msg);
2132 void BufferView::showDialog(string const & name)
2135 d->gui_->showDialog(name, string());
2139 void BufferView::showDialog(string const & name,
2140 string const & data, Inset * inset)
2143 d->gui_->showDialog(name, data, inset);
2147 void BufferView::updateDialog(string const & name, string const & data)
2150 d->gui_->updateDialog(name, data);
2154 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2160 // FIXME: Move this out of BufferView again
2161 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2163 if (!fname.isReadableFile()) {
2164 docstring const error = from_ascii(strerror(errno));
2165 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2166 docstring const text =
2167 bformat(_("Could not read the specified document\n"
2168 "%1$s\ndue to the error: %2$s"), file, error);
2169 Alert::error(_("Could not read file"), text);
2173 if (!fname.isReadableFile()) {
2174 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2175 docstring const text =
2176 bformat(_("%1$s\n is not readable."), file);
2177 Alert::error(_("Could not open file"), text);
2181 // FIXME UNICODE: We don't know the encoding of the file
2182 docstring file_content = fname.fileContents("UTF-8");
2183 if (file_content.empty()) {
2184 Alert::error(_("Reading not UTF-8 encoded file"),
2185 _("The file is not UTF-8 encoded.\n"
2186 "It will be read as local 8Bit-encoded.\n"
2187 "If this does not give the correct result\n"
2188 "then please change the encoding of the file\n"
2189 "to UTF-8 with a program other than LyX.\n"));
2190 file_content = fname.fileContents("local8bit");
2193 return normalize_c(file_content);
2197 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2199 docstring const tmpstr = contentsOfPlaintextFile(f);
2204 Cursor & cur = cursor();
2205 cap::replaceSelection(cur);
2206 buffer_.undo().recordUndo(cur);
2208 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2210 cur.innerText()->insertStringAsLines(cur, tmpstr);
2217 docstring const & BufferView::inlineCompletion() const
2219 return d->inlineCompletion;
2223 size_t const & BufferView::inlineCompletionUniqueChars() const
2225 return d->inlineCompletionUniqueChars;
2229 DocIterator const & BufferView::inlineCompletionPos() const
2231 return d->inlineCompletionPos;
2235 bool samePar(DocIterator const & a, DocIterator const & b)
2237 if (a.empty() && b.empty())
2239 if (a.empty() || b.empty())
2241 return &a.innerParagraph() == &b.innerParagraph();
2245 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2246 docstring const & completion, size_t uniqueChars)
2248 uniqueChars = min(completion.size(), uniqueChars);
2249 bool changed = d->inlineCompletion != completion
2250 || d->inlineCompletionUniqueChars != uniqueChars;
2251 bool singlePar = true;
2252 d->inlineCompletion = completion;
2253 d->inlineCompletionUniqueChars = min(completion.size(), uniqueChars);
2255 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2258 DocIterator const & old = d->inlineCompletionPos;
2260 //lyxerr << "inlineCompletionPos changed" << std::endl;
2261 // old or pos are in another paragraph?
2262 if ((!samePar(cur, pos) && !pos.empty())
2263 || (!samePar(cur, old) && !old.empty())) {
2265 //lyxerr << "different paragraph" << std::endl;
2267 d->inlineCompletionPos = pos;
2272 if (singlePar && !(cur.disp_.update() & Update::Force))
2273 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2275 cur.updateFlags(cur.disp_.update() | Update::Force);