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"
53 #include "WordLangTuple.h"
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetCommand.h" // ChangeRefs
57 #include "insets/InsetRef.h"
58 #include "insets/InsetText.h"
60 #include "frontends/alert.h"
61 #include "frontends/Application.h"
62 #include "frontends/Delegates.h"
63 #include "frontends/FontMetrics.h"
64 #include "frontends/Painter.h"
65 #include "frontends/Selection.h"
67 #include "graphics/Previews.h"
69 #include "support/convert.h"
70 #include "support/debug.h"
71 #include "support/ExceptionMessage.h"
72 #include "support/filetools.h"
73 #include "support/gettext.h"
74 #include "support/lstrings.h"
75 #include "support/Package.h"
76 #include "support/types.h"
85 using namespace lyx::support;
89 namespace Alert = frontend::Alert;
93 /// Return an inset of this class if it exists at the current cursor position
95 T * getInsetByCode(Cursor const & cur, InsetCode code)
98 Inset * inset = it.nextInset();
99 if (inset && inset->lyxCode() == code)
100 return static_cast<T*>(inset);
105 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
108 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
109 docstring const & contents)
111 DocIterator tmpdit = dit;
114 Inset const * inset = tmpdit.nextInset();
116 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
117 && (contents.empty() ||
118 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
122 tmpdit.forwardInset();
129 /// Looks for next inset with one of the given codes.
130 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
134 DocIterator tmpdit = dit;
135 tmpdit.forwardInset();
140 Inset const * inset = tmpdit.nextInset();
142 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
143 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
147 if (!findNextInset(tmpdit, codes, contents)) {
148 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
149 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
150 if (!findNextInset(tmpdit, codes, contents))
161 /// Looks for next inset with the given code
162 void findInset(DocIterator & dit, InsetCode code, bool same_content)
164 findInset(dit, vector<InsetCode>(1, code), same_content);
168 /// Moves cursor to the next inset with one of the given codes.
169 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
172 Cursor tmpcur = bv->cursor();
173 if (!findInset(tmpcur, codes, same_content)) {
174 bv->cursor().message(_("No more insets"));
178 tmpcur.clearSelection();
179 bv->setCursor(tmpcur);
184 /// Moves cursor to the next inset with given code.
185 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
187 gotoInset(bv, vector<InsetCode>(1, code), same_content);
191 /// A map from a Text to the associated text metrics
192 typedef map<Text const *, TextMetrics> TextMetricsCache;
194 enum ScreenUpdateStrategy {
204 /////////////////////////////////////////////////////////////////////
208 /////////////////////////////////////////////////////////////////////
210 struct BufferView::Private
212 Private(BufferView & bv): wh_(0), cursor_(bv),
213 anchor_pit_(0), anchor_ypos_(0),
214 last_inset_(0), gui_(0)
218 ScrollbarParameters scrollbarParameters_;
220 ScreenUpdateStrategy update_strategy_;
222 CoordCache coord_cache_;
224 /// Estimated average par height for scrollbar.
226 /// this is used to handle XSelection events in the right manner.
235 pit_type anchor_pit_;
239 vector<int> par_height_;
242 DocIterator inlineCompletionPos;
244 docstring inlineCompletion;
246 size_t inlineCompletionUniqueChars;
248 /// keyboard mapping object.
251 /// last visited inset.
252 /** kept to send setMouseHover(false).
253 * Not owned, so don't delete.
257 mutable TextMetricsCache text_metrics_;
260 /** Not owned, so don't delete.
262 frontend::GuiBufferViewDelegate * gui_;
266 BufferView::BufferView(Buffer & buf)
267 : width_(0), height_(0), full_screen_(false), buffer_(buf), d(new Private(*this))
269 d->xsel_cache_.set = false;
270 d->intl_.initKeyMapper(lyxrc.use_kbmap);
272 d->cursor_.push(buffer_.inset());
273 d->cursor_.resetAnchor();
274 d->cursor_.setCurrentFont();
276 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
277 graphics::Previews::get().generateBufferPreviews(buffer_);
281 BufferView::~BufferView()
283 // current buffer is going to be switched-off, save cursor pos
284 // Ideally, the whole cursor stack should be saved, but session
285 // currently can only handle bottom (whole document) level pit and pos.
286 // That is to say, if a cursor is in a nested inset, it will be
287 // restore to the left of the top level inset.
288 LastFilePosSection::FilePos fp;
289 fp.pit = d->cursor_.bottom().pit();
290 fp.pos = d->cursor_.bottom().pos();
291 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
297 int BufferView::rightMargin() const
299 // The additional test for the case the outliner is opened.
301 !lyxrc.full_screen_limit ||
302 width_ < lyxrc.full_screen_width + 20)
305 return (width_ - lyxrc.full_screen_width) / 2;
309 int BufferView::leftMargin() const
311 return rightMargin();
315 Intl & BufferView::getIntl()
321 Intl const & BufferView::getIntl() const
327 CoordCache & BufferView::coordCache()
329 return d->coord_cache_;
333 CoordCache const & BufferView::coordCache() const
335 return d->coord_cache_;
339 Buffer & BufferView::buffer()
345 Buffer const & BufferView::buffer() const
351 bool BufferView::fitCursor()
353 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
354 frontend::FontMetrics const & fm =
355 theFontMetrics(d->cursor_.getFont().fontInfo());
356 int const asc = fm.maxAscent();
357 int const des = fm.maxDescent();
358 Point const p = getPos(d->cursor_, d->cursor_.boundary());
359 if (p.y_ - asc >= 0 && p.y_ + des < height_)
366 void BufferView::processUpdateFlags(Update::flags flags)
368 // last_inset_ points to the last visited inset. This pointer may become
369 // invalid because of keyboard editing. Since all such operations
370 // causes screen update(), I reset last_inset_ to avoid such a problem.
372 // This is close to a hot-path.
373 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
374 << "[fitcursor = " << (flags & Update::FitCursor)
375 << ", forceupdate = " << (flags & Update::Force)
376 << ", singlepar = " << (flags & Update::SinglePar)
377 << "] buffer: " << &buffer_);
379 buffer_.updateMacros();
381 // Now do the first drawing step if needed. This consists on updating
382 // the CoordCache in updateMetrics().
383 // The second drawing step is done in WorkArea::redraw() if needed.
385 // Case when no explicit update is requested.
387 // no need to redraw anything.
388 d->update_strategy_ = NoScreenUpdate;
392 if (flags == Update::Decoration) {
393 d->update_strategy_ = DecorationUpdate;
398 if (flags == Update::FitCursor
399 || flags == (Update::Decoration | Update::FitCursor)) {
400 // tell the frontend to update the screen if needed.
405 if (flags & Update::Decoration) {
406 d->update_strategy_ = DecorationUpdate;
410 // no screen update is needed.
411 d->update_strategy_ = NoScreenUpdate;
415 bool const full_metrics = flags & Update::Force || !singleParUpdate();
418 // We have to update the full screen metrics.
421 if (!(flags & Update::FitCursor)) {
422 // Nothing to do anymore. Trigger a redraw and return
427 // updateMetrics() does not update paragraph position
428 // This is done at draw() time. So we need a redraw!
432 // The cursor is off screen so ensure it is visible.
439 void BufferView::updateScrollbar()
444 // We prefer fixed size line scrolling.
445 d->scrollbarParameters_.single_step = defaultRowHeight();
446 // We prefer full screen page scrolling.
447 d->scrollbarParameters_.page_step = height_;
449 Text & t = buffer_.text();
450 TextMetrics & tm = d->text_metrics_[&t];
452 LYXERR(Debug::GUI, " Updating scrollbar: height: "
453 << t.paragraphs().size()
454 << " curr par: " << d->cursor_.bottom().pit()
455 << " default height " << defaultRowHeight());
457 size_t const parsize = t.paragraphs().size();
458 if (d->par_height_.size() != parsize) {
459 d->par_height_.clear();
460 // FIXME: We assume a default paragraph height of 2 rows. This
461 // should probably be pondered with the screen width.
462 d->par_height_.resize(parsize, defaultRowHeight() * 2);
465 // Look at paragraph heights on-screen
466 pair<pit_type, ParagraphMetrics const *> first = tm.first();
467 pair<pit_type, ParagraphMetrics const *> last = tm.last();
468 for (pit_type pit = first.first; pit <= last.first; ++pit) {
469 d->par_height_[pit] = tm.parMetrics(pit).height();
470 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
471 << d->par_height_[pit]);
474 int top_pos = first.second->position() - first.second->ascent();
475 int bottom_pos = last.second->position() + last.second->descent();
476 bool first_visible = first.first == 0 && top_pos >= 0;
477 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
478 if (first_visible && last_visible) {
479 d->scrollbarParameters_.min = 0;
480 d->scrollbarParameters_.max = 0;
484 d->scrollbarParameters_.min = top_pos;
485 for (size_t i = 0; i != size_t(first.first); ++i)
486 d->scrollbarParameters_.min -= d->par_height_[i];
487 d->scrollbarParameters_.max = bottom_pos;
488 for (size_t i = last.first + 1; i != parsize; ++i)
489 d->scrollbarParameters_.max += d->par_height_[i];
491 d->scrollbarParameters_.position = 0;
492 // The reference is the top position so we remove one page.
493 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
497 ScrollbarParameters const & BufferView::scrollbarParameters() const
499 return d->scrollbarParameters_;
503 docstring BufferView::toolTip(int x, int y) const
505 // Get inset under mouse, if there is one.
506 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
508 // No inset, no tooltip...
510 return covering_inset->toolTip(*this, x, y);
514 docstring BufferView::contextMenu(int x, int y) const
516 // Get inset under mouse, if there is one.
517 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
519 return covering_inset->contextMenu(*this, x, y);
521 // FIXME: Do something more elaborate here.
522 return from_ascii("edit");
526 void BufferView::scrollDocView(int value)
528 int const offset = value - d->scrollbarParameters_.position;
529 // If the offset is less than 2 screen height, prefer to scroll instead.
530 if (abs(offset) <= 2 * height_) {
535 // cut off at the top
536 if (value <= d->scrollbarParameters_.min) {
537 DocIterator dit = doc_iterator_begin(buffer_.inset());
539 LYXERR(Debug::SCROLLING, "scroll to top");
543 // cut off at the bottom
544 if (value >= d->scrollbarParameters_.max) {
545 DocIterator dit = doc_iterator_end(buffer_.inset());
548 LYXERR(Debug::SCROLLING, "scroll to bottom");
552 // find paragraph at target position
553 int par_pos = d->scrollbarParameters_.min;
555 for (; i != int(d->par_height_.size()); ++i) {
556 par_pos += d->par_height_[i];
557 if (par_pos >= value)
561 if (par_pos < value) {
562 // It seems we didn't find the correct pit so stay on the safe side and
564 LYXERR0("scrolling position not found!");
565 scrollDocView(d->scrollbarParameters_.max);
569 DocIterator dit = doc_iterator_begin(buffer_.inset());
571 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
576 // FIXME: this method is not working well.
577 void BufferView::setCursorFromScrollbar()
579 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
581 int const height = 2 * defaultRowHeight();
582 int const first = height;
583 int const last = height_ - height;
584 Cursor & cur = d->cursor_;
586 switch (cursorStatus(cur)) {
588 // We reset the cursor because cursorStatus() does not
589 // work when the cursor is within mathed.
590 cur.reset(buffer_.inset());
591 tm.setCursorFromCoordinates(cur, 0, first);
592 cur.clearSelection();
595 // We reset the cursor because cursorStatus() does not
596 // work when the cursor is within mathed.
597 cur.reset(buffer_.inset());
598 tm.setCursorFromCoordinates(cur, 0, last);
599 cur.clearSelection();
602 int const y = getPos(cur, cur.boundary()).y_;
603 int const newy = min(last, max(y, first));
605 cur.reset(buffer_.inset());
606 tm.setCursorFromCoordinates(cur, 0, newy);
612 Change const BufferView::getCurrentChange() const
614 if (!d->cursor_.selection())
615 return Change(Change::UNCHANGED);
617 DocIterator dit = d->cursor_.selectionBegin();
618 return dit.paragraph().lookupChange(dit.pos());
622 // this could be used elsewhere as well?
623 // FIXME: This does not work within mathed!
624 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
626 Point const p = getPos(dit, dit.boundary());
629 if (p.y_ > workHeight())
635 void BufferView::saveBookmark(unsigned int idx)
637 // tenatively save bookmark, id and pos will be used to
638 // acturately locate a bookmark in a 'live' lyx session.
639 // pit and pos will be updated with bottom level pit/pos
641 LyX::ref().session().bookmarks().save(
643 d->cursor_.bottom().pit(),
644 d->cursor_.bottom().pos(),
645 d->cursor_.paragraph().id(),
650 // emit message signal.
651 message(_("Save bookmark"));
655 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
656 int top_id, pos_type top_pos)
658 bool success = false;
661 d->cursor_.clearSelection();
663 // if a valid par_id is given, try it first
664 // This is the case for a 'live' bookmark when unique paragraph ID
665 // is used to track bookmarks.
667 dit = buffer_.getParFromID(top_id);
669 dit.pos() = min(dit.paragraph().size(), top_pos);
670 // Some slices of the iterator may not be
671 // reachable (e.g. closed collapsable inset)
672 // so the dociterator may need to be
673 // shortened. Otherwise, setCursor may crash
674 // lyx when the cursor can not be set to these
676 size_t const n = dit.depth();
677 for (size_t i = 0; i < n; ++i)
678 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
686 // if top_id == 0, or searching through top_id failed
687 // This is the case for a 'restored' bookmark when only bottom
688 // (document level) pit was saved. Because of this, bookmark
689 // restoration is inaccurate. If a bookmark was within an inset,
690 // it will be restored to the left of the outmost inset that contains
692 if (bottom_pit < int(buffer_.paragraphs().size())) {
693 dit = doc_iterator_begin(buffer_.inset());
695 dit.pit() = bottom_pit;
696 dit.pos() = min(bottom_pos, dit.paragraph().size());
701 // Note: only bottom (document) level pit is set.
703 // set the current font.
704 d->cursor_.setCurrentFont();
705 // To center the screen on this new position we need the
706 // paragraph position which is computed at draw() time.
707 // So we need a redraw!
717 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
719 if (lyxrc.rtl_support) {
720 if (d->cursor_.real_current_font.isRightToLeft()) {
721 if (d->intl_.keymap == Intl::PRIMARY)
722 d->intl_.keyMapSec();
724 if (d->intl_.keymap == Intl::SECONDARY)
725 d->intl_.keyMapPrim();
729 d->intl_.getTransManager().translateAndInsert(c, t, cur);
733 int BufferView::workWidth() const
739 void BufferView::showCursor()
741 showCursor(d->cursor_);
745 void BufferView::showCursor(DocIterator const & dit)
747 // We are not properly started yet, delay until resizing is
752 LYXERR(Debug::SCROLLING, "recentering!");
754 CursorSlice const & bot = dit.bottom();
755 TextMetrics & tm = d->text_metrics_[bot.text()];
757 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
758 int bot_pit = bot.pit();
759 if (bot_pit > max_pit) {
760 // FIXME: Why does this happen?
761 LYXERR0("bottom pit is greater that max pit: "
762 << bot_pit << " > " << max_pit);
766 if (bot_pit == tm.first().first - 1)
767 tm.newParMetricsUp();
768 else if (bot_pit == tm.last().first + 1)
769 tm.newParMetricsDown();
771 if (tm.contains(bot_pit)) {
772 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
773 BOOST_ASSERT(!pm.rows().empty());
774 // FIXME: smooth scrolling doesn't work in mathed.
775 CursorSlice const & cs = dit.innerTextSlice();
776 int offset = coordOffset(dit, dit.boundary()).y_;
777 int ypos = pm.position() + offset;
778 Dimension const & row_dim =
779 pm.getRow(cs.pos(), dit.boundary()).dimension();
780 if (ypos - row_dim.ascent() < 0)
781 scrollUp(- ypos + row_dim.ascent());
782 else if (ypos + row_dim.descent() > height_)
783 scrollDown(ypos - height_ + row_dim.descent());
784 // else, nothing to do, the cursor is already visible so we just return.
788 // fix inline completion position
789 if (d->inlineCompletionPos.fixIfBroken())
790 d->inlineCompletionPos = DocIterator();
792 tm.redoParagraph(bot_pit);
793 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
794 int offset = coordOffset(dit, dit.boundary()).y_;
796 d->anchor_pit_ = bot_pit;
797 CursorSlice const & cs = dit.innerTextSlice();
798 Dimension const & row_dim =
799 pm.getRow(cs.pos(), dit.boundary()).dimension();
801 if (d->anchor_pit_ == 0)
802 d->anchor_ypos_ = offset + pm.ascent();
803 else if (d->anchor_pit_ == max_pit)
804 d->anchor_ypos_ = height_ - offset - row_dim.descent();
806 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
813 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
817 Cursor & cur = d->cursor_;
819 switch (cmd.action) {
822 flag.enabled(buffer_.undo().hasUndoStack());
825 flag.enabled(buffer_.undo().hasRedoStack());
827 case LFUN_FILE_INSERT:
828 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
829 case LFUN_FILE_INSERT_PLAINTEXT:
830 case LFUN_BOOKMARK_SAVE:
831 // FIXME: Actually, these LFUNS should be moved to Text
832 flag.enabled(cur.inTexted());
834 case LFUN_FONT_STATE:
835 case LFUN_LABEL_INSERT:
836 case LFUN_INFO_INSERT:
837 case LFUN_PARAGRAPH_GOTO:
839 case LFUN_REFERENCE_NEXT:
841 case LFUN_WORD_REPLACE:
844 case LFUN_MARK_TOGGLE:
845 case LFUN_SCREEN_RECENTER:
846 case LFUN_BIBTEX_DATABASE_ADD:
847 case LFUN_BIBTEX_DATABASE_DEL:
848 case LFUN_STATISTICS:
849 case LFUN_NEXT_INSET_TOGGLE:
853 case LFUN_LABEL_GOTO: {
854 flag.enabled(!cmd.argument().empty()
855 || getInsetByCode<InsetRef>(cur, REF_CODE));
859 case LFUN_CHANGES_TRACK:
861 flag.setOnOff(buffer_.params().trackChanges);
864 case LFUN_CHANGES_OUTPUT:
866 flag.setOnOff(buffer_.params().outputChanges);
869 case LFUN_CHANGES_MERGE:
870 case LFUN_CHANGE_NEXT:
871 case LFUN_ALL_CHANGES_ACCEPT:
872 case LFUN_ALL_CHANGES_REJECT:
873 // TODO: context-sensitive enabling of LFUNs
874 // In principle, these command should only be enabled if there
875 // is a change in the document. However, without proper
876 // optimizations, this will inevitably result in poor performance.
880 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
881 flag.setOnOff(buffer_.params().compressed);
885 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
886 flag.setOnOff(buffer_.params().embedded);
891 case LFUN_SCREEN_DOWN:
896 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
897 // everywhere else before this can enabled:
898 case LFUN_SCREEN_UP_SELECT:
899 case LFUN_SCREEN_DOWN_SELECT:
903 case LFUN_LAYOUT_TABULAR:
904 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
908 case LFUN_LAYOUT_PARAGRAPH:
909 flag.enabled(cur.inset().allowParagraphCustomization(cur.idx()));
912 case LFUN_INSET_SETTINGS: {
913 InsetCode code = cur.inset().lyxCode();
917 enable = cmd.argument() == "tabular";
920 enable = cmd.argument() == "ert";
923 enable = cmd.argument() == "float";
926 enable = cmd.argument() == "wrap";
929 enable = cmd.argument() == "note";
932 enable = cmd.argument() == "branch";
935 enable = cmd.argument() == "box";
938 enable = cmd.argument() == "listings";
943 flag.enabled(enable);
947 case LFUN_DIALOG_SHOW_NEW_INSET:
948 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
949 cur.inset().lyxCode() != LISTINGS_CODE);
950 if (cur.inset().lyxCode() == CAPTION_CODE) {
952 if (cur.inset().getStatus(cur, cmd, flag))
965 bool BufferView::dispatch(FuncRequest const & cmd)
967 //lyxerr << [ cmd = " << cmd << "]" << endl;
969 // Make sure that the cached BufferView is correct.
970 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
971 << " arg[" << to_utf8(cmd.argument()) << ']'
972 << " x[" << cmd.x << ']'
973 << " y[" << cmd.y << ']'
974 << " button[" << cmd.button() << ']');
976 Cursor & cur = d->cursor_;
978 switch (cmd.action) {
981 cur.message(_("Undo"));
982 cur.clearSelection();
984 cur.message(_("No further undo information"));
986 processUpdateFlags(Update::Force | Update::FitCursor);
990 cur.message(_("Redo"));
991 cur.clearSelection();
993 cur.message(_("No further redo information"));
995 processUpdateFlags(Update::Force | Update::FitCursor);
998 case LFUN_FONT_STATE:
999 cur.message(cur.currentState());
1002 case LFUN_BOOKMARK_SAVE:
1003 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1006 case LFUN_LABEL_GOTO: {
1007 docstring label = cmd.argument();
1008 if (label.empty()) {
1010 getInsetByCode<InsetRef>(d->cursor_,
1013 label = inset->getParam("reference");
1014 // persistent=false: use temp_bookmark
1024 case LFUN_PARAGRAPH_GOTO: {
1025 int const id = convert<int>(to_utf8(cmd.argument()));
1027 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1028 b = theBufferList().next(b)) {
1030 DocIterator dit = b->getParFromID(id);
1032 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1036 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1037 << " found in buffer `"
1038 << b->absFileName() << "'.");
1040 if (b == &buffer_) {
1043 processUpdateFlags(Update::Force | Update::FitCursor);
1045 // Switch to other buffer view and resend cmd
1046 theLyXFunc().dispatch(FuncRequest(
1047 LFUN_BUFFER_SWITCH, b->absFileName()));
1048 theLyXFunc().dispatch(cmd);
1055 case LFUN_NOTE_NEXT:
1056 gotoInset(this, NOTE_CODE, false);
1059 case LFUN_REFERENCE_NEXT: {
1060 vector<InsetCode> tmp;
1061 tmp.push_back(LABEL_CODE);
1062 tmp.push_back(REF_CODE);
1063 gotoInset(this, tmp, true);
1067 case LFUN_CHANGES_TRACK:
1068 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1071 case LFUN_CHANGES_OUTPUT:
1072 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1073 if (buffer_.params().outputChanges) {
1074 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1075 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1076 LaTeXFeatures::isAvailable("xcolor");
1078 if (!dvipost && !xcolorsoul) {
1079 Alert::warning(_("Changes not shown in LaTeX output"),
1080 _("Changes will not be highlighted in LaTeX output, "
1081 "because neither dvipost nor xcolor/soul are installed.\n"
1082 "Please install these packages or redefine "
1083 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1084 } else if (!xcolorsoul) {
1085 Alert::warning(_("Changes not shown in LaTeX output"),
1086 _("Changes will not be highlighted in LaTeX output "
1087 "when using pdflatex, because xcolor and soul are not installed.\n"
1088 "Please install both packages or redefine "
1089 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1094 case LFUN_CHANGE_NEXT:
1095 findNextChange(this);
1098 case LFUN_CHANGES_MERGE:
1099 if (findNextChange(this))
1100 showDialog("changes");
1103 case LFUN_ALL_CHANGES_ACCEPT:
1104 // select complete document
1105 d->cursor_.reset(buffer_.inset());
1106 d->cursor_.selHandle(true);
1107 buffer_.text().cursorBottom(d->cursor_);
1108 // accept everything in a single step to support atomic undo
1109 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1112 case LFUN_ALL_CHANGES_REJECT:
1113 // select complete document
1114 d->cursor_.reset(buffer_.inset());
1115 d->cursor_.selHandle(true);
1116 buffer_.text().cursorBottom(d->cursor_);
1117 // reject everything in a single step to support atomic undo
1118 // Note: reject does not work recursively; the user may have to repeat the operation
1119 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1122 case LFUN_WORD_FIND:
1123 if (find(this, cmd))
1126 message(_("String not found!"));
1129 case LFUN_WORD_REPLACE: {
1130 bool has_deleted = false;
1131 if (cur.selection()) {
1132 DocIterator beg = cur.selectionBegin();
1133 DocIterator end = cur.selectionEnd();
1134 if (beg.pit() == end.pit()) {
1135 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1136 if (cur.paragraph().isDeleted(p))
1141 replace(this, cmd, has_deleted);
1146 cur.clearSelection();
1148 cur.message(from_utf8(N_("Mark off")));
1152 cur.clearSelection();
1155 cur.message(from_utf8(N_("Mark on")));
1158 case LFUN_MARK_TOGGLE:
1159 cur.clearSelection();
1162 cur.message(from_utf8(N_("Mark removed")));
1165 cur.message(from_utf8(N_("Mark set")));
1170 case LFUN_SCREEN_RECENTER:
1174 case LFUN_BIBTEX_DATABASE_ADD: {
1175 Cursor tmpcur = d->cursor_;
1176 findInset(tmpcur, BIBTEX_CODE, false);
1177 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1180 if (inset->addDatabase(to_utf8(cmd.argument())))
1181 buffer_.updateBibfilesCache();
1186 case LFUN_BIBTEX_DATABASE_DEL: {
1187 Cursor tmpcur = d->cursor_;
1188 findInset(tmpcur, BIBTEX_CODE, false);
1189 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1192 if (inset->delDatabase(to_utf8(cmd.argument())))
1193 buffer_.updateBibfilesCache();
1198 case LFUN_STATISTICS: {
1199 DocIterator from, to;
1200 if (cur.selection()) {
1201 from = cur.selectionBegin();
1202 to = cur.selectionEnd();
1204 from = doc_iterator_begin(buffer_.inset());
1205 to = doc_iterator_end(buffer_.inset());
1207 int const words = countWords(from, to);
1208 int const chars = countChars(from, to, false);
1209 int const chars_blanks = countChars(from, to, true);
1211 if (cur.selection())
1212 message = _("Statistics for the selection:");
1214 message = _("Statistics for the document:");
1217 message += bformat(_("%1$d words"), words);
1219 message += _("One word");
1221 if (chars_blanks != 1)
1222 message += bformat(_("%1$d characters (including blanks)"),
1225 message += _("One character (including blanks)");
1228 message += bformat(_("%1$d characters (excluding blanks)"),
1231 message += _("One character (excluding blanks)");
1233 Alert::information(_("Statistics"), message);
1237 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1238 // turn compression on/off
1239 buffer_.params().compressed = !buffer_.params().compressed;
1242 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
1243 // turn embedding on/off
1245 buffer_.embeddedFiles().enable(!buffer_.params().embedded, buffer_);
1246 } catch (ExceptionMessage const & message) {
1247 Alert::error(message.title_, message.details_);
1252 case LFUN_NEXT_INSET_TOGGLE: {
1253 // this is the real function we want to invoke
1254 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1255 // if there is an inset at cursor, see whether it
1257 Inset * inset = cur.nextInset();
1259 if (inset->isActive()) {
1260 Cursor tmpcur = cur;
1261 tmpcur.pushBackward(*inset);
1262 inset->dispatch(tmpcur, tmpcmd);
1263 if (tmpcur.result().dispatched()) {
1266 } else if (inset->editable() == Inset::IS_EDITABLE) {
1267 inset->edit(cur, true);
1270 // if it did not work, try the underlying inset.
1271 if (!cur.result().dispatched())
1272 cur.dispatch(tmpcmd);
1274 if (!cur.result().dispatched())
1275 // It did not work too; no action needed.
1277 cur.clearSelection();
1278 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1282 case LFUN_SCREEN_UP:
1283 case LFUN_SCREEN_DOWN: {
1284 Point p = getPos(cur, cur.boundary());
1285 if (p.y_ < 0 || p.y_ > height_) {
1286 // The cursor is off-screen so recenter before proceeding.
1288 p = getPos(cur, cur.boundary());
1290 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1291 cur.reset(buffer_.inset());
1292 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1293 //FIXME: what to do with cur.x_target()?
1302 case LFUN_SCREEN_UP_SELECT:
1303 case LFUN_SCREEN_DOWN_SELECT: {
1304 // Those two are not ready yet for consumption.
1307 cur.selHandle(true);
1308 size_t initial_depth = cur.depth();
1309 Point const p = getPos(cur, cur.boundary());
1310 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1311 // FIXME: We need to verify if the cursor stayed within an inset...
1312 //cur.reset(buffer_.inset());
1313 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1315 while (cur.depth() > initial_depth) {
1318 // FIXME: we need to do a redraw again because of the selection
1319 // But no screen update is needed.
1320 d->update_strategy_ = NoScreenUpdate;
1333 docstring const BufferView::requestSelection()
1335 Cursor & cur = d->cursor_;
1337 if (!cur.selection()) {
1338 d->xsel_cache_.set = false;
1342 if (!d->xsel_cache_.set ||
1343 cur.top() != d->xsel_cache_.cursor ||
1344 cur.anchor_.top() != d->xsel_cache_.anchor)
1346 d->xsel_cache_.cursor = cur.top();
1347 d->xsel_cache_.anchor = cur.anchor_.top();
1348 d->xsel_cache_.set = cur.selection();
1349 return cur.selectionAsString(false);
1355 void BufferView::clearSelection()
1357 d->cursor_.clearSelection();
1358 // Clear the selection buffer. Otherwise a subsequent
1359 // middle-mouse-button paste would use the selection buffer,
1360 // not the more current external selection.
1361 cap::clearSelection();
1362 d->xsel_cache_.set = false;
1363 // The buffer did not really change, but this causes the
1364 // redraw we need because we cleared the selection above.
1369 void BufferView::resize(int width, int height)
1371 // Update from work area
1375 // Clear the paragraph height cache.
1376 d->par_height_.clear();
1377 // Redo the metrics.
1382 Inset const * BufferView::getCoveringInset(Text const & text,
1385 TextMetrics & tm = d->text_metrics_[&text];
1386 Inset * inset = tm.checkInsetHit(x, y);
1390 if (!inset->descendable())
1391 // No need to go further down if the inset is not
1395 size_t cell_number = inset->nargs();
1396 // Check all the inner cell.
1397 for (size_t i = 0; i != cell_number; ++i) {
1398 Text const * inner_text = inset->getText(i);
1401 Inset const * inset_deeper =
1402 getCoveringInset(*inner_text, x, y);
1404 return inset_deeper;
1412 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1414 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1416 // This is only called for mouse related events including
1417 // LFUN_FILE_OPEN generated by drag-and-drop.
1418 FuncRequest cmd = cmd0;
1420 Cursor old = cursor();
1422 cur.push(buffer_.inset());
1423 cur.selection() = d->cursor_.selection();
1425 // Either the inset under the cursor or the
1426 // surrounding Text will handle this event.
1428 // make sure we stay within the screen...
1429 cmd.y = min(max(cmd.y, -1), height_);
1431 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1433 // Get inset under mouse, if there is one.
1434 Inset const * covering_inset =
1435 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1436 if (covering_inset == d->last_inset_)
1437 // Same inset, no need to do anything...
1440 bool need_redraw = false;
1441 // const_cast because of setMouseHover().
1442 Inset * inset = const_cast<Inset *>(covering_inset);
1444 // Remove the hint on the last hovered inset (if any).
1445 need_redraw |= d->last_inset_->setMouseHover(false);
1447 // Highlighted the newly hovered inset (if any).
1448 need_redraw |= inset->setMouseHover(true);
1449 d->last_inset_ = inset;
1453 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1454 << cmd.x << ", " << cmd.y << ")");
1456 d->update_strategy_ = DecorationUpdate;
1458 // This event (moving without mouse click) is not passed further.
1459 // This should be changed if it is further utilized.
1464 // Build temporary cursor.
1465 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1467 // Put anchor at the same position.
1470 // Try to dispatch to an non-editable inset near this position
1471 // via the temp cursor. If the inset wishes to change the real
1472 // cursor it has to do so explicitly by using
1473 // cur.bv().cursor() = cur; (or similar)
1475 inset->dispatch(cur, cmd);
1477 // Now dispatch to the temporary cursor. If the real cursor should
1478 // be modified, the inset's dispatch has to do so explicitly.
1479 if (!cur.result().dispatched())
1482 // Notify left insets
1485 bool badcursor = notifyCursorLeaves(old, cur);
1487 cursor().fixIfBroken();
1490 // Do we have a selection?
1491 theSelection().haveSelection(cursor().selection());
1493 // If the command has been dispatched,
1494 if (cur.result().dispatched() || cur.result().update())
1495 processUpdateFlags(cur.result().update());
1499 void BufferView::lfunScroll(FuncRequest const & cmd)
1501 string const scroll_type = cmd.getArg(0);
1502 int const scroll_step =
1503 (scroll_type == "line")? d->scrollbarParameters_.single_step
1504 : (scroll_type == "page")? d->scrollbarParameters_.page_step : 0;
1505 if (scroll_step == 0)
1507 string const scroll_quantity = cmd.getArg(1);
1508 if (scroll_quantity == "up")
1509 scrollUp(scroll_step);
1510 else if (scroll_quantity == "down")
1511 scrollDown(scroll_step);
1513 int const scroll_value = convert<int>(scroll_quantity);
1515 scroll(scroll_step * scroll_value);
1520 void BufferView::scroll(int y)
1529 void BufferView::scrollDown(int offset)
1531 Text * text = &buffer_.text();
1532 TextMetrics & tm = d->text_metrics_[text];
1533 int ymax = height_ + offset;
1535 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1536 int bottom_pos = last.second->position() + last.second->descent();
1537 if (last.first + 1 == int(text->paragraphs().size())) {
1538 if (bottom_pos <= height_)
1540 offset = min(offset, bottom_pos - height_);
1543 if (bottom_pos > ymax)
1545 tm.newParMetricsDown();
1547 d->anchor_ypos_ -= offset;
1553 void BufferView::scrollUp(int offset)
1555 Text * text = &buffer_.text();
1556 TextMetrics & tm = d->text_metrics_[text];
1557 int ymin = - offset;
1559 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1560 int top_pos = first.second->position() - first.second->ascent();
1561 if (first.first == 0) {
1564 offset = min(offset, - top_pos);
1569 tm.newParMetricsUp();
1571 d->anchor_ypos_ += offset;
1577 void BufferView::setCursorFromRow(int row)
1582 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1584 d->cursor_.reset(buffer_.inset());
1586 buffer_.text().setCursor(d->cursor_, 0, 0);
1588 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1592 void BufferView::gotoLabel(docstring const & label)
1594 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1595 vector<docstring> labels;
1596 it->getLabelList(labels);
1597 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1606 TextMetrics const & BufferView::textMetrics(Text const * t) const
1608 return const_cast<BufferView *>(this)->textMetrics(t);
1612 TextMetrics & BufferView::textMetrics(Text const * t)
1614 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1615 if (tmc_it == d->text_metrics_.end()) {
1616 tmc_it = d->text_metrics_.insert(
1617 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1619 return tmc_it->second;
1623 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1626 return textMetrics(t).parMetrics(pit);
1630 int BufferView::workHeight() const
1636 void BufferView::setCursor(DocIterator const & dit)
1638 size_t const n = dit.depth();
1639 for (size_t i = 0; i < n; ++i)
1640 dit[i].inset().edit(d->cursor_, true);
1642 d->cursor_.setCursor(dit);
1643 d->cursor_.selection() = false;
1647 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1649 // Would be wrong to delete anything if we have a selection.
1650 if (cur.selection())
1653 bool need_anchor_change = false;
1654 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1655 need_anchor_change);
1657 if (need_anchor_change)
1665 updateLabels(buffer_);
1673 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1675 BOOST_ASSERT(&cur.bv() == this);
1678 // this event will clear selection so we save selection for
1679 // persistent selection
1680 cap::saveSelection(cursor());
1682 // Has the cursor just left the inset?
1683 bool badcursor = false;
1684 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1686 d->cursor_.fixIfBroken();
1687 badcursor = notifyCursorLeaves(d->cursor_, cur);
1692 // FIXME: shift-mouse selection doesn't work well across insets.
1693 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1695 // do the dEPM magic if needed
1696 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1697 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1698 // the leftinset bool would not be necessary (badcursor instead).
1699 bool update = leftinset;
1700 if (!do_selection && !badcursor && d->cursor_.inTexted())
1701 update |= checkDepm(cur, d->cursor_);
1703 d->cursor_.setCursor(cur);
1704 d->cursor_.boundary(cur.boundary());
1706 d->cursor_.setSelection();
1708 d->cursor_.clearSelection();
1710 d->cursor_.finishUndo();
1711 d->cursor_.setCurrentFont();
1716 void BufferView::putSelectionAt(DocIterator const & cur,
1717 int length, bool backwards)
1719 d->cursor_.clearSelection();
1725 d->cursor_.pos() += length;
1726 d->cursor_.setSelection(d->cursor_, -length);
1728 d->cursor_.setSelection(d->cursor_, length);
1730 // Ensure a redraw happens in any case because the new selection could
1731 // possibly be on the same screen as the previous selection.
1732 processUpdateFlags(Update::Force | Update::FitCursor);
1736 Cursor & BufferView::cursor()
1742 Cursor const & BufferView::cursor() const
1748 pit_type BufferView::anchor_ref() const
1750 return d->anchor_pit_;
1754 bool BufferView::singleParUpdate()
1756 Text & buftext = buffer_.text();
1757 pit_type const bottom_pit = d->cursor_.bottom().pit();
1758 TextMetrics & tm = textMetrics(&buftext);
1759 int old_height = tm.parMetrics(bottom_pit).height();
1761 // make sure inline completion pointer is ok
1762 if (d->inlineCompletionPos.fixIfBroken())
1763 d->inlineCompletionPos = DocIterator();
1765 // In Single Paragraph mode, rebreak only
1766 // the (main text, not inset!) paragraph containing the cursor.
1767 // (if this paragraph contains insets etc., rebreaking will
1768 // recursively descend)
1769 tm.redoParagraph(bottom_pit);
1770 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1771 if (pm.height() != old_height)
1772 // Paragraph height has changed so we cannot proceed to
1773 // the singlePar optimisation.
1776 d->update_strategy_ = SingleParUpdate;
1778 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1779 << " y2: " << pm.position() + pm.descent()
1780 << " pit: " << bottom_pit
1781 << " singlepar: 1");
1786 void BufferView::updateMetrics()
1788 Text & buftext = buffer_.text();
1789 pit_type const npit = int(buftext.paragraphs().size());
1791 // Clear out the position cache in case of full screen redraw,
1792 d->coord_cache_.clear();
1794 // Clear out paragraph metrics to avoid having invalid metrics
1795 // in the cache from paragraphs not relayouted below
1796 // The complete text metrics will be redone.
1797 d->text_metrics_.clear();
1799 TextMetrics & tm = textMetrics(&buftext);
1801 // make sure inline completion pointer is ok
1802 if (d->inlineCompletionPos.fixIfBroken())
1803 d->inlineCompletionPos = DocIterator();
1805 if (d->anchor_pit_ >= npit)
1806 // The anchor pit must have been deleted...
1807 d->anchor_pit_ = npit - 1;
1809 // Rebreak anchor paragraph.
1810 tm.redoParagraph(d->anchor_pit_);
1811 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1814 if (d->anchor_pit_ == 0) {
1815 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
1817 // Complete buffer visible? Then it's easy.
1818 if (scrollRange == 0)
1819 d->anchor_ypos_ = anchor_pm.ascent();
1821 // FIXME: Some clever handling needed to show
1822 // the _first_ paragraph up to the top if the cursor is
1823 // in the first line.
1825 anchor_pm.setPosition(d->anchor_ypos_);
1827 LYXERR(Debug::PAINTING, "metrics: "
1828 << " anchor pit = " << d->anchor_pit_
1829 << " anchor ypos = " << d->anchor_ypos_);
1831 // Redo paragraphs above anchor if necessary.
1832 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1833 // We are now just above the anchor paragraph.
1834 pit_type pit1 = d->anchor_pit_ - 1;
1835 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1836 tm.redoParagraph(pit1);
1837 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1839 // Save the paragraph position in the cache.
1844 // Redo paragraphs below the anchor if necessary.
1845 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1846 // We are now just below the anchor paragraph.
1847 pit_type pit2 = d->anchor_pit_ + 1;
1848 for (; pit2 < npit && y2 <= height_; ++pit2) {
1849 tm.redoParagraph(pit2);
1850 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1852 // Save the paragraph position in the cache.
1857 LYXERR(Debug::PAINTING, "Metrics: "
1858 << " anchor pit = " << d->anchor_pit_
1859 << " anchor ypos = " << d->anchor_ypos_
1862 << " pit1 = " << pit1
1863 << " pit2 = " << pit2);
1865 d->update_strategy_ = FullScreenUpdate;
1867 if (lyxerr.debugging(Debug::WORKAREA)) {
1868 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1869 d->coord_cache_.dump();
1874 void BufferView::insertLyXFile(FileName const & fname)
1876 BOOST_ASSERT(d->cursor_.inTexted());
1878 // Get absolute path of file and add ".lyx"
1879 // to the filename if necessary
1880 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1882 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1883 // emit message signal.
1884 message(bformat(_("Inserting document %1$s..."), disp_fn));
1887 Buffer buf("", false);
1888 if (buf.loadLyXFile(filename)) {
1889 ErrorList & el = buffer_.errorList("Parse");
1890 // Copy the inserted document error list into the current buffer one.
1891 el = buf.errorList("Parse");
1892 buffer_.undo().recordUndo(d->cursor_);
1893 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1894 buf.params().documentClassPtr(), el);
1895 res = _("Document %1$s inserted.");
1897 res = _("Could not insert document %1$s");
1902 // emit message signal.
1903 message(bformat(res, disp_fn));
1904 buffer_.errors("Parse");
1908 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1914 // Addup contribution of nested insets, from inside to outside,
1915 // keeping the outer paragraph for a special handling below
1916 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1917 CursorSlice const & sl = dit[i];
1921 // get relative position inside sl.inset()
1922 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1924 // Make relative position inside of the edited inset relative to sl.inset()
1928 // In case of an RTL inset, the edited inset will be positioned to the left
1931 bool boundary_i = boundary && i + 1 == dit.depth();
1932 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1937 // remember width for the case that sl.inset() is positioned in an RTL inset
1938 if (i && dit[i - 1].text()) {
1939 // If this Inset is inside a Text Inset, retrieve the Dimension
1940 // from the containing text instead of using Inset::dimension() which
1941 // might not be implemented.
1942 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1943 // elimination of Inset::dim_ cache. This coordOffset() method needs
1944 // to be rewritten in light of the new design.
1945 Dimension const & dim = parMetrics(dit[i - 1].text(),
1946 dit[i - 1].pit()).insetDimension(&sl.inset());
1949 Dimension const dim = sl.inset().dimension(*this);
1953 //lyxerr << "Cursor::getPos, i: "
1954 // << i << " x: " << xx << " y: " << y << endl;
1957 // Add contribution of initial rows of outermost paragraph
1958 CursorSlice const & sl = dit[0];
1959 TextMetrics const & tm = textMetrics(sl.text());
1960 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1961 BOOST_ASSERT(!pm.rows().empty());
1962 y -= pm.rows()[0].ascent();
1964 // FIXME: document this mess
1966 if (sl.pos() > 0 && dit.depth() == 1) {
1968 if (pos && boundary)
1970 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1971 rend = pm.pos2row(pos);
1973 rend = pm.pos2row(sl.pos());
1975 size_t rend = pm.pos2row(sl.pos());
1977 for (size_t rit = 0; rit != rend; ++rit)
1978 y += pm.rows()[rit].height();
1979 y += pm.rows()[rend].ascent();
1981 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1983 // Make relative position from the nested inset now bufferview absolute.
1984 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1987 // In the RTL case place the nested inset at the left of the cursor in
1988 // the outer paragraph
1989 bool boundary_1 = boundary && 1 == dit.depth();
1990 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1998 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2000 CursorSlice const & bot = dit.bottom();
2001 TextMetrics const & tm = textMetrics(bot.text());
2002 if (!tm.contains(bot.pit()))
2003 return Point(-1, -1);
2005 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2006 p.y_ += tm.parMetrics(bot.pit()).position();
2011 void BufferView::draw(frontend::Painter & pain)
2013 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2014 Text & text = buffer_.text();
2015 TextMetrics const & tm = d->text_metrics_[&text];
2016 int const y = tm.first().second->position();
2017 PainterInfo pi(this, pain);
2019 switch (d->update_strategy_) {
2021 case NoScreenUpdate:
2022 // If no screen painting is actually needed, only some the different
2023 // coordinates of insets and paragraphs needs to be updated.
2024 pi.full_repaint = true;
2025 pi.pain.setDrawingEnabled(false);
2029 case SingleParUpdate:
2030 pi.full_repaint = false;
2031 // In general, only the current row of the outermost paragraph
2032 // will be redrawn. Particular cases where selection spans
2033 // multiple paragraph are correctly detected in TextMetrics.
2037 case DecorationUpdate:
2038 // FIXME: We should also distinguish DecorationUpdate to avoid text
2039 // drawing if possible. This is not possible to do easily right now
2040 // because of the single backing pixmap.
2042 case FullScreenUpdate:
2043 // The whole screen, including insets, will be refreshed.
2044 pi.full_repaint = true;
2046 // Clear background.
2047 pain.fillRectangle(0, 0, width_, height_,
2048 buffer_.inset().backgroundColor());
2053 // and possibly grey out below
2054 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2055 int const y2 = lastpm.second->position() + lastpm.second->descent();
2057 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2060 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2062 // The scrollbar needs an update.
2065 // Normalize anchor for next time
2066 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2067 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2068 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2069 ParagraphMetrics const & pm = tm.parMetrics(pit);
2070 if (pm.position() + pm.descent() > 0) {
2071 d->anchor_pit_ = pit;
2072 d->anchor_ypos_ = pm.position();
2076 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2077 << " anchor ypos = " << d->anchor_ypos_);
2081 void BufferView::message(docstring const & msg)
2084 d->gui_->message(msg);
2088 void BufferView::showDialog(string const & name)
2091 d->gui_->showDialog(name, string());
2095 void BufferView::showDialog(string const & name,
2096 string const & data, Inset * inset)
2099 d->gui_->showDialog(name, data, inset);
2103 void BufferView::updateDialog(string const & name, string const & data)
2106 d->gui_->updateDialog(name, data);
2110 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2116 // FIXME: Move this out of BufferView again
2117 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2119 if (!fname.isReadableFile()) {
2120 docstring const error = from_ascii(strerror(errno));
2121 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2122 docstring const text =
2123 bformat(_("Could not read the specified document\n"
2124 "%1$s\ndue to the error: %2$s"), file, error);
2125 Alert::error(_("Could not read file"), text);
2129 if (!fname.isReadableFile()) {
2130 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2131 docstring const text =
2132 bformat(_("%1$s\n is not readable."), file);
2133 Alert::error(_("Could not open file"), text);
2137 // FIXME UNICODE: We don't know the encoding of the file
2138 docstring file_content = fname.fileContents("UTF-8");
2139 if (file_content.empty()) {
2140 Alert::error(_("Reading not UTF-8 encoded file"),
2141 _("The file is not UTF-8 encoded.\n"
2142 "It will be read as local 8Bit-encoded.\n"
2143 "If this does not give the correct result\n"
2144 "then please change the encoding of the file\n"
2145 "to UTF-8 with a program other than LyX.\n"));
2146 file_content = fname.fileContents("local8bit");
2149 return normalize_c(file_content);
2153 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2155 docstring const tmpstr = contentsOfPlaintextFile(f);
2160 Cursor & cur = cursor();
2161 cap::replaceSelection(cur);
2162 buffer_.undo().recordUndo(cur);
2164 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2166 cur.innerText()->insertStringAsLines(cur, tmpstr);
2173 docstring const & BufferView::inlineCompletion() const
2175 return d->inlineCompletion;
2179 size_t const & BufferView::inlineCompletionUniqueChars() const
2181 return d->inlineCompletionUniqueChars;
2185 DocIterator const & BufferView::inlineCompletionPos() const
2187 return d->inlineCompletionPos;
2191 bool samePar(DocIterator const & a, DocIterator const & b)
2193 if (a.empty() && b.empty())
2195 if (a.empty() || b.empty())
2197 return &a.innerParagraph() == &b.innerParagraph();
2201 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2202 docstring const & completion, size_t uniqueChars)
2204 uniqueChars = min(completion.size(), uniqueChars);
2205 bool changed = d->inlineCompletion != completion
2206 || d->inlineCompletionUniqueChars != uniqueChars;
2207 bool singlePar = true;
2208 d->inlineCompletion = completion;
2209 d->inlineCompletionUniqueChars = min(completion.size(), uniqueChars);
2211 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2214 DocIterator const & old = d->inlineCompletionPos;
2216 //lyxerr << "inlineCompletionPos changed" << std::endl;
2217 // old or pos are in another paragraph?
2218 if ((!samePar(cur, pos) && !pos.empty())
2219 || (!samePar(cur, old) && !old.empty())) {
2221 //lyxerr << "different paragraph" << std::endl;
2223 d->inlineCompletionPos = pos;
2228 if (singlePar && !(cur.disp_.update() & Update::Force))
2229 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2231 cur.updateFlags(cur.disp_.update() | Update::Force);