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 "bufferview_funcs.h"
24 #include "coordcache.h"
25 #include "CutAndPaste.h"
27 #include "dispatchresult.h"
28 #include "errorlist.h"
30 #include "FloatList.h"
31 #include "funcrequest.h"
32 #include "FuncStatus.h"
35 #include "insetiterator.h"
37 #include "LaTeXFeatures.h"
38 #include "lyx_cb.h" // added for Dispatch functions
42 #include "lyxlayout.h"
44 #include "lyxtextclass.h"
47 #include "paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "pariterator.h"
55 #include "WordLangTuple.h"
56 #include "metricsinfo.h"
58 #include "insets/insetbibtex.h"
59 #include "insets/insetcommand.h" // ChangeRefs
60 #include "insets/insetref.h"
61 #include "insets/insettext.h"
63 #include "frontends/Alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
67 #include "graphics/Previews.h"
69 #include "support/convert.h"
70 #include "support/filefilterlist.h"
71 #include "support/filetools.h"
72 #include "support/package.h"
73 #include "support/types.h"
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
84 using support::addPath;
85 using support::bformat;
86 using support::FileFilterList;
87 using support::FileName;
88 using support::fileSearch;
89 using support::isDirWriteable;
90 using support::isFileReadable;
91 using support::makeDisplayPath;
92 using support::package;
96 using std::istringstream;
100 using std::mem_fun_ref;
104 namespace Alert = frontend::Alert;
108 /// Return an inset of this class if it exists at the current cursor position
110 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
113 DocIterator it = cur;
114 if (it.nextInset() &&
115 it.nextInset()->lyxCode() == code) {
116 inset = static_cast<T*>(it.nextInset());
124 BufferView::BufferView()
125 : width_(0), height_(0), buffer_(0), wh_(0),
127 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 intl_(new Intl), last_inset_(0)
130 xsel_cache_.set = false;
131 intl_->initKeyMapper(lyxrc.use_kbmap);
135 BufferView::~BufferView()
140 Buffer * BufferView::buffer() const
146 void BufferView::setBuffer(Buffer * b)
148 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149 << "[ b = " << b << "]" << endl;
152 // Save the actual cursor position and anchor inside the
153 // buffer so that it can be restored in case we rechange
154 // to this buffer later on.
155 buffer_->saveCursor(cursor_.selectionBegin(),
156 cursor_.selectionEnd());
157 // update bookmark pit of the current buffer before switch
158 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
159 BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
160 if (buffer()->fileName() != bm.filename.absFilename())
162 // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
163 // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
167 boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
168 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
169 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
171 // current buffer is going to be switched-off, save cursor pos
172 // Ideally, the whole cursor stack should be saved, but session
173 // currently can only handle bottom (whole document) level pit and pos.
174 // That is to say, if a cursor is in a nested inset, it will be
175 // restore to the left of the top level inset.
176 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
177 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
180 // If we're quitting lyx, don't bother updating stuff
186 // If we are closing current buffer, switch to the first in
189 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
190 << " No Buffer!" << endl;
191 // We are closing the buffer, use the first buffer as current
192 buffer_ = theBufferList().first();
194 // Set current buffer
199 cursor_ = LCursor(*this);
204 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
205 << "Buffer addr: " << buffer_ << endl;
206 cursor_.push(buffer_->inset());
207 cursor_.resetAnchor();
208 buffer_->text().setCurrentFont(cursor_);
209 if (buffer_->getCursor().size() > 0 &&
210 buffer_->getAnchor().size() > 0)
212 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
213 cursor_.resetAnchor();
214 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
215 cursor_.setSelection();
216 // do not set selection to the new buffer because we
217 // only paste recent selection.
222 updateMetrics(false);
224 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
225 graphics::Previews::get().generateBufferPreviews(*buffer_);
229 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
231 // File already open?
232 if (theBufferList().exists(filename.absFilename())) {
233 docstring const file = makeDisplayPath(filename.absFilename(), 20);
234 docstring text = bformat(_("The document %1$s is already "
235 "loaded.\n\nDo you want to revert "
236 "to the saved version?"), file);
237 int const ret = Alert::prompt(_("Revert to saved document?"),
238 text, 0, 1, _("&Revert"), _("&Switch to document"));
241 setBuffer(theBufferList().getBuffer(filename.absFilename()));
244 // FIXME: should be LFUN_REVERT
245 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
247 // Fall through to new load. (Asger)
253 if (isFileReadable(filename)) {
254 b = theBufferList().newBuffer(filename.absFilename());
255 if (!lyx::loadLyXFile(b, filename)) {
256 theBufferList().release(b);
260 docstring text = bformat(_("The document %1$s does not yet "
261 "exist.\n\nDo you want to create "
262 "a new document?"), from_utf8(filename.absFilename()));
263 int const ret = Alert::prompt(_("Create new document?"),
264 text, 0, 1, _("&Create"), _("Cancel"));
267 b = newFile(filename.absFilename(), string(), true);
275 // Send the "errors" signal in case of parsing errors
278 // Update the labels and section numbering.
279 updateLabels(*buffer_);
280 // scroll to the position when the file was last closed
281 if (lyxrc.use_lastfilepos) {
284 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
285 // if successfully move to pit (returned par_id is not zero), update metrics and reset font
286 if (moveToPosition(pit, pos, 0, 0).get<1>()) {
288 updateMetrics(false);
289 buffer_->text().setCurrentFont(cursor_);
294 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
300 void BufferView::resize()
305 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
307 updateMetrics(false);
312 bool BufferView::fitCursor()
314 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
315 frontend::FontMetrics const & fm =
316 theFontMetrics(cursor_.getFont());
317 int const asc = fm.maxAscent();
318 int const des = fm.maxDescent();
319 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
320 if (p.y_ - asc >= 0 && p.y_ + des < height_)
328 bool BufferView::multiParSel()
330 if (!cursor_.selection())
332 bool ret = multiparsel_cache_;
333 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
334 // Either this, or previous selection spans paragraphs
335 return ret || multiparsel_cache_;
339 bool BufferView::update(Update::flags flags)
341 // last_inset_ points to the last visited inset. This pointer may become
342 // invalid because of keyboard editing. Since all such operations
343 // causes screen update(), I reset last_inset_ to avoid such a problem.
345 // This is close to a hot-path.
347 << BOOST_CURRENT_FUNCTION
348 << "[fitcursor = " << (flags & Update::FitCursor)
349 << ", forceupdate = " << (flags & Update::Force)
350 << ", singlepar = " << (flags & Update::SinglePar)
351 << "] buffer: " << buffer_ << endl;
353 // Check needed to survive LyX startup
357 LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
359 // Update macro store
360 buffer_->buildMacros();
362 // Now do the first drawing step if needed. This consists on updating
363 // the CoordCache in updateMetrics().
364 // The second drawing step is done in WorkArea::redraw() if needed.
366 // Case when no explicit update is requested.
368 // no need to redraw anything.
369 metrics_info_.update_strategy = NoScreenUpdate;
373 if (flags == Update::Decoration) {
374 metrics_info_.update_strategy = DecorationUpdate;
378 if (flags == Update::FitCursor
379 || flags == (Update::Decoration | Update::FitCursor)) {
380 bool const fit_cursor = fitCursor();
381 // tell the frontend to update the screen if needed.
383 updateMetrics(false);
386 if (flags & Update::Decoration) {
387 metrics_info_.update_strategy = DecorationUpdate;
390 // no screen update is needed.
391 metrics_info_.update_strategy = NoScreenUpdate;
395 bool full_metrics = flags & Update::Force;
396 if (flags & Update::MultiParSel)
397 full_metrics |= multiParSel();
399 bool const single_par = !full_metrics;
400 updateMetrics(single_par);
402 if (flags & Update::FitCursor && fitCursor())
403 updateMetrics(false);
405 // tell the frontend to update the screen.
410 void BufferView::updateScrollbar()
413 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
414 << " no text in updateScrollbar" << endl;
415 scrollbarParameters_.reset();
419 LyXText & t = buffer_->text();
420 TextMetrics & tm = text_metrics_[&t];
422 int const parsize = int(t.paragraphs().size() - 1);
423 if (anchor_ref_ > parsize) {
424 anchor_ref_ = parsize;
429 << BOOST_CURRENT_FUNCTION
430 << " Updating scrollbar: height: " << t.paragraphs().size()
431 << " curr par: " << cursor_.bottom().pit()
432 << " default height " << defaultRowHeight() << endl;
434 // It would be better to fix the scrollbar to understand
435 // values in [0..1] and divide everything by wh
437 // estimated average paragraph height:
441 int h = tm.parMetrics(anchor_ref_).height();
443 // Normalize anchor/offset (MV):
444 while (offset_ref_ > h && anchor_ref_ < parsize) {
447 h = tm.parMetrics(anchor_ref_).height();
449 // Look at paragraph heights on-screen
452 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
455 int const h2 = tm.parMetrics(pit).height();
461 int const hav = sumh / nh;
462 // More realistic average paragraph height
467 scrollbarParameters_.height = (parsize + 1) * wh_;
468 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
469 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
473 ScrollbarParameters const & BufferView::scrollbarParameters() const
475 return scrollbarParameters_;
479 void BufferView::scrollDocView(int value)
481 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
482 << "[ value = " << value << "]" << endl;
487 LyXText & t = buffer_->text();
488 TextMetrics & tm = text_metrics_[&t];
490 float const bar = value / float(wh_ * t.paragraphs().size());
492 anchor_ref_ = int(bar * t.paragraphs().size());
493 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
494 anchor_ref_ = int(t.paragraphs().size()) - 1;
496 tm.redoParagraph(anchor_ref_);
497 int const h = tm.parMetrics(anchor_ref_).height();
498 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
499 updateMetrics(false);
503 void BufferView::setCursorFromScrollbar()
508 LyXText & t = buffer_->text();
510 int const height = 2 * defaultRowHeight();
511 int const first = height;
512 int const last = height_ - height;
513 LCursor & cur = cursor_;
515 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
518 case bv_funcs::CUR_ABOVE:
519 // We reset the cursor because bv_funcs::status() does not
520 // work when the cursor is within mathed.
521 cur.reset(buffer_->inset());
522 t.setCursorFromCoordinates(cur, 0, first);
523 cur.clearSelection();
525 case bv_funcs::CUR_BELOW:
526 // We reset the cursor because bv_funcs::status() does not
527 // work when the cursor is within mathed.
528 cur.reset(buffer_->inset());
529 t.setCursorFromCoordinates(cur, 0, last);
530 cur.clearSelection();
532 case bv_funcs::CUR_INSIDE:
533 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
534 int const newy = min(last, max(y, first));
536 cur.reset(buffer_->inset());
537 t.setCursorFromCoordinates(cur, 0, newy);
543 Change const BufferView::getCurrentChange() const
545 if (!cursor_.selection())
546 return Change(Change::UNCHANGED);
548 DocIterator dit = cursor_.selectionBegin();
549 return dit.paragraph().lookupChange(dit.pos());
553 void BufferView::saveBookmark(unsigned int idx)
555 // tenatively save bookmark, id and pos will be used to
556 // acturately locate a bookmark in a 'live' lyx session.
557 // pit and pos will be updated with bottom level pit/pos
559 LyX::ref().session().bookmarks().save(
560 FileName(buffer_->fileName()),
561 cursor_.bottom().pit(),
562 cursor_.bottom().pos(),
563 cursor_.paragraph().id(),
568 // emit message signal.
569 message(_("Save bookmark"));
573 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
574 int top_id, pos_type top_pos)
576 cursor_.clearSelection();
578 // if a valid par_id is given, try it first
579 // This is the case for a 'live' bookmark when unique paragraph ID
580 // is used to track bookmarks.
582 ParIterator par = buffer_->getParFromID(top_id);
583 if (par != buffer_->par_iterator_end()) {
584 setCursor(makeDocIterator(par, min(par->size(), top_pos)));
585 // Note: return bottom (document) level pit.
586 return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
589 // if top_id == 0, or searching through top_id failed
590 // This is the case for a 'restored' bookmark when only bottom
591 // (document level) pit was saved. Because of this, bookmark
592 // restoration is inaccurate. If a bookmark was within an inset,
593 // it will be restored to the left of the outmost inset that contains
595 if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
596 ParIterator it = buffer_->par_iterator_begin();
597 ParIterator const end = buffer_->par_iterator_end();
598 for (; it != end; ++it)
599 if (it.pit() == bottom_pit) {
600 // restored pos may be bigger than it->size
601 setCursor(makeDocIterator(it, min(bottom_pos, it->size())));
602 return boost::make_tuple(bottom_pit, bottom_pos, it->id());
606 return boost::make_tuple(pit_type(0), pos_type(0), 0);
610 void BufferView::switchKeyMap()
612 if (!lyxrc.rtl_support)
615 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
616 if (intl_->keymap == Intl::PRIMARY)
619 if (intl_->keymap == Intl::SECONDARY)
625 int BufferView::workWidth() const
631 void BufferView::center()
633 CursorSlice & bot = cursor_.bottom();
634 TextMetrics & tm = text_metrics_[bot.text()];
635 pit_type const pit = bot.pit();
636 tm.redoParagraph(pit);
637 ParagraphMetrics const & pm = tm.parMetrics(pit);
639 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
640 + pm.ascent() - height_ / 2;
644 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
648 switch (cmd.action) {
651 flag.enabled(!buffer_->undostack().empty());
654 flag.enabled(!buffer_->redostack().empty());
656 case LFUN_FILE_INSERT:
657 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
658 case LFUN_FILE_INSERT_PLAINTEXT:
659 case LFUN_BOOKMARK_SAVE:
660 // FIXME: Actually, these LFUNS should be moved to LyXText
661 flag.enabled(cursor_.inTexted());
663 case LFUN_FONT_STATE:
664 case LFUN_LABEL_INSERT:
665 case LFUN_PARAGRAPH_GOTO:
666 // FIXME handle non-trivially
667 case LFUN_OUTLINE_UP:
668 case LFUN_OUTLINE_DOWN:
669 case LFUN_OUTLINE_IN:
670 case LFUN_OUTLINE_OUT:
672 case LFUN_REFERENCE_NEXT:
674 case LFUN_WORD_REPLACE:
677 case LFUN_MARK_TOGGLE:
678 case LFUN_SCREEN_RECENTER:
679 case LFUN_BIBTEX_DATABASE_ADD:
680 case LFUN_BIBTEX_DATABASE_DEL:
681 case LFUN_WORDS_COUNT:
682 case LFUN_NEXT_INSET_TOGGLE:
686 case LFUN_LABEL_GOTO: {
687 flag.enabled(!cmd.argument().empty()
688 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
692 case LFUN_CHANGES_TRACK:
694 flag.setOnOff(buffer_->params().trackChanges);
697 case LFUN_CHANGES_OUTPUT:
698 flag.enabled(buffer_ && LaTeXFeatures::isAvailable("dvipost"));
699 flag.setOnOff(buffer_->params().outputChanges);
702 case LFUN_CHANGES_MERGE:
703 case LFUN_CHANGE_NEXT:
704 case LFUN_ALL_CHANGES_ACCEPT:
705 case LFUN_ALL_CHANGES_REJECT:
706 // TODO: context-sensitive enabling of LFUNs
707 // In principle, these command should only be enabled if there
708 // is a change in the document. However, without proper
709 // optimizations, this will inevitably result in poor performance.
710 flag.enabled(buffer_);
713 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
714 flag.setOnOff(buffer_->params().compressed);
726 Update::flags BufferView::dispatch(FuncRequest const & cmd)
728 //lyxerr << BOOST_CURRENT_FUNCTION
729 // << [ cmd = " << cmd << "]" << endl;
731 // Make sure that the cached BufferView is correct.
732 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
733 << " action[" << cmd.action << ']'
734 << " arg[" << to_utf8(cmd.argument()) << ']'
735 << " x[" << cmd.x << ']'
736 << " y[" << cmd.y << ']'
737 << " button[" << cmd.button() << ']'
740 // FIXME: this should not be possible.
744 LCursor & cur = cursor_;
745 // Default Update flags.
746 Update::flags updateFlags = Update::Force | Update::FitCursor;
748 switch (cmd.action) {
751 cur.message(_("Undo"));
752 cur.clearSelection();
753 if (!textUndo(*this)) {
754 cur.message(_("No further undo information"));
755 updateFlags = Update::None;
761 cur.message(_("Redo"));
762 cur.clearSelection();
763 if (!textRedo(*this)) {
764 cur.message(_("No further redo information"));
765 updateFlags = Update::None;
770 case LFUN_FILE_INSERT:
772 menuInsertLyXFile(to_utf8(cmd.argument()));
775 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
777 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
780 case LFUN_FILE_INSERT_PLAINTEXT:
782 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
785 case LFUN_FONT_STATE:
786 cur.message(cur.currentState());
789 case LFUN_BOOKMARK_SAVE:
790 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
793 case LFUN_LABEL_GOTO: {
794 docstring label = cmd.argument();
797 getInsetByCode<InsetRef>(cursor_,
798 InsetBase::REF_CODE);
800 label = inset->getParam("reference");
801 // persistent=false: use temp_bookmark
811 case LFUN_PARAGRAPH_GOTO: {
812 int const id = convert<int>(to_utf8(cmd.argument()));
814 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
815 ParIterator par = b->getParFromID(id);
816 if (par == b->par_iterator_end()) {
818 << "No matching paragraph found! ["
819 << id << "]." << endl;
822 << "Paragraph " << par->id()
823 << " found in buffer `"
824 << b->fileName() << "'." << endl;
828 setCursor(makeDocIterator(par, 0));
831 // Switch to other buffer view and resend cmd
832 theLyXFunc().dispatch(FuncRequest(
833 LFUN_BUFFER_SWITCH, b->fileName()));
834 theLyXFunc().dispatch(cmd);
835 updateFlags = Update::None;
844 case LFUN_OUTLINE_UP:
845 toc::outline(toc::Up, cursor_);
846 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
847 updateLabels(*buffer_);
849 case LFUN_OUTLINE_DOWN:
850 toc::outline(toc::Down, cursor_);
851 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
852 updateLabels(*buffer_);
854 case LFUN_OUTLINE_IN:
855 toc::outline(toc::In, cursor_);
856 updateLabels(*buffer_);
858 case LFUN_OUTLINE_OUT:
859 toc::outline(toc::Out, cursor_);
860 updateLabels(*buffer_);
864 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
867 case LFUN_REFERENCE_NEXT: {
868 vector<InsetBase_code> tmp;
869 tmp.push_back(InsetBase::LABEL_CODE);
870 tmp.push_back(InsetBase::REF_CODE);
871 bv_funcs::gotoInset(this, tmp, true);
875 case LFUN_CHANGES_TRACK:
876 buffer_->params().trackChanges = !buffer_->params().trackChanges;
879 case LFUN_CHANGES_OUTPUT:
880 buffer_->params().outputChanges = !buffer_->params().outputChanges;
883 case LFUN_CHANGE_NEXT:
884 findNextChange(this);
887 case LFUN_CHANGES_MERGE:
888 if (findNextChange(this))
889 showDialog("changes");
892 case LFUN_ALL_CHANGES_ACCEPT:
893 // select complete document
894 cursor_.reset(buffer_->inset());
895 cursor_.selHandle(true);
896 buffer_->text().cursorBottom(cursor_);
897 // accept everything in a single step to support atomic undo
898 buffer_->text().acceptOrRejectChanges(cursor_, LyXText::ACCEPT);
901 case LFUN_ALL_CHANGES_REJECT:
902 // select complete document
903 cursor_.reset(buffer_->inset());
904 cursor_.selHandle(true);
905 buffer_->text().cursorBottom(cursor_);
906 // reject everything in a single step to support atomic undo
907 // Note: reject does not work recursively; the user may have to repeat the operation
908 buffer_->text().acceptOrRejectChanges(cursor_, LyXText::REJECT);
915 case LFUN_WORD_REPLACE:
920 cur.clearSelection();
922 cur.message(from_utf8(N_("Mark off")));
926 cur.clearSelection();
929 cur.message(from_utf8(N_("Mark on")));
932 case LFUN_MARK_TOGGLE:
933 cur.clearSelection();
936 cur.message(from_utf8(N_("Mark removed")));
939 cur.message(from_utf8(N_("Mark set")));
944 case LFUN_SCREEN_RECENTER:
948 case LFUN_BIBTEX_DATABASE_ADD: {
949 LCursor tmpcur = cursor_;
950 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
951 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
952 InsetBase::BIBTEX_CODE);
954 if (inset->addDatabase(to_utf8(cmd.argument())))
955 buffer_->updateBibfilesCache();
960 case LFUN_BIBTEX_DATABASE_DEL: {
961 LCursor tmpcur = cursor_;
962 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
963 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
964 InsetBase::BIBTEX_CODE);
966 if (inset->delDatabase(to_utf8(cmd.argument())))
967 buffer_->updateBibfilesCache();
972 case LFUN_WORDS_COUNT: {
973 DocIterator from, to;
974 if (cur.selection()) {
975 from = cur.selectionBegin();
976 to = cur.selectionEnd();
978 from = doc_iterator_begin(buffer_->inset());
979 to = doc_iterator_end(buffer_->inset());
981 int const count = countWords(from, to);
985 message = bformat(_("%1$d words in selection."),
988 message = bformat(_("%1$d words in document."),
993 message = _("One word in selection.");
995 message = _("One word in document.");
998 Alert::information(_("Count words"), message);
1002 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1003 // turn compression on/off
1004 buffer_->params().compressed = !buffer_->params().compressed;
1007 case LFUN_NEXT_INSET_TOGGLE: {
1008 // this is the real function we want to invoke
1009 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1010 // if there is an inset at cursor, see whether it
1012 InsetBase * inset = cur.nextInset();
1013 if (inset && inset->isActive()) {
1014 LCursor tmpcur = cur;
1015 tmpcur.pushLeft(*inset);
1016 inset->dispatch(tmpcur, tmpcmd);
1017 if (tmpcur.result().dispatched()) {
1021 // if it did not work, try the underlying inset.
1022 if (!cur.result().dispatched())
1023 cur.dispatch(tmpcmd);
1025 if (cur.result().dispatched())
1026 cur.clearSelection();
1032 updateFlags = Update::None;
1039 docstring const BufferView::requestSelection()
1044 LCursor & cur = cursor_;
1046 if (!cur.selection()) {
1047 xsel_cache_.set = false;
1051 if (!xsel_cache_.set ||
1052 cur.top() != xsel_cache_.cursor ||
1053 cur.anchor_.top() != xsel_cache_.anchor)
1055 xsel_cache_.cursor = cur.top();
1056 xsel_cache_.anchor = cur.anchor_.top();
1057 xsel_cache_.set = cur.selection();
1058 return cur.selectionAsString(false);
1064 void BufferView::clearSelection()
1067 cursor_.clearSelection();
1068 // Clear the selection buffer. Otherwise a subsequent
1069 // middle-mouse-button paste would use the selection buffer,
1070 // not the more current external selection.
1071 cap::clearSelection();
1072 xsel_cache_.set = false;
1073 // The buffer did not really change, but this causes the
1074 // redraw we need because we cleared the selection above.
1080 void BufferView::workAreaResize(int width, int height)
1082 // Update from work area
1086 // The complete text metrics will be redone.
1087 text_metrics_.clear();
1094 InsetBase const * BufferView::getCoveringInset(LyXText const & text, int x, int y)
1096 pit_type pit = text.getPitNearY(*this, y);
1097 BOOST_ASSERT(pit != -1);
1098 Paragraph const & par = text.getPar(pit);
1100 LYXERR(Debug::DEBUG)
1101 << BOOST_CURRENT_FUNCTION
1106 InsetList::const_iterator iit = par.insetlist.begin();
1107 InsetList::const_iterator iend = par.insetlist.end();
1108 for (; iit != iend; ++iit) {
1109 InsetBase * const inset = iit->inset;
1110 if (inset->covers(*this, x, y)) {
1111 if (!inset->descendable())
1112 // No need to go further down if the inset is not
1116 size_t cell_number = inset->nargs();
1117 // Check all the inner cell.
1118 for (size_t i = 0; i != cell_number; ++i) {
1119 LyXText const * inner_text = inset->getText(i);
1122 InsetBase const * inset_deeper =
1123 getCoveringInset(*inner_text, x, y);
1125 return inset_deeper;
1129 LYXERR(Debug::DEBUG)
1130 << BOOST_CURRENT_FUNCTION
1131 << ": Hit inset: " << inset << endl;
1135 LYXERR(Debug::DEBUG)
1136 << BOOST_CURRENT_FUNCTION
1137 << ": No inset hit. " << endl;
1142 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1144 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1146 // This is only called for mouse related events including
1147 // LFUN_FILE_OPEN generated by drag-and-drop.
1148 FuncRequest cmd = cmd0;
1150 // E.g. Qt mouse press when no buffer
1155 cur.push(buffer_->inset());
1156 cur.selection() = cursor_.selection();
1158 // Either the inset under the cursor or the
1159 // surrounding LyXText will handle this event.
1161 // make sure we stay within the screen...
1162 cmd.y = min(max(cmd.y, -1), height_);
1164 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1166 // Get inset under mouse, if there is one.
1167 InsetBase const * covering_inset =
1168 getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1169 if (covering_inset == last_inset_)
1170 // Same inset, no need to do anything...
1173 bool need_redraw = false;
1174 // const_cast because of setMouseHover().
1175 InsetBase * inset = const_cast<InsetBase *>(covering_inset);
1177 // Remove the hint on the last hovered inset (if any).
1178 need_redraw |= last_inset_->setMouseHover(false);
1180 // Highlighted the newly hovered inset (if any).
1181 need_redraw |= inset->setMouseHover(true);
1182 last_inset_ = inset;
1184 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1185 // not expose the button for redraw. We adjust here the metrics dimension
1186 // to enable a full redraw.
1187 // FIXME: It is possible to redraw only the area around the button!
1189 && metrics_info_.update_strategy == SingleParUpdate) {
1190 // FIXME: It should be possible to redraw only the area around
1191 // the button by doing this:
1193 //metrics_info_.singlepar = false;
1194 //metrics_info_.y1 = ymin of button;
1195 //metrics_info_.y2 = ymax of button;
1197 // Unfortunately, rowpainter.C:paintText() does not distinguish
1198 // between background updates and text updates. So we use the hammer
1199 // solution for now. We could also avoid the updateMetrics() below
1200 // by using the first and last pit of the CoordCache. Have a look
1201 // at LyXText::getPitNearY() to see what I mean.
1203 //metrics_info_.pit1 = first pit of CoordCache;
1204 //metrics_info_.pit2 = last pit of CoordCache;
1205 //metrics_info_.singlepar = false;
1206 //metrics_info_.y1 = 0;
1207 //metrics_info_.y2 = height_;
1209 updateMetrics(false);
1212 // This event (moving without mouse click) is not passed further.
1213 // This should be changed if it is further utilized.
1217 // Build temporary cursor.
1218 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1220 // Put anchor at the same position.
1223 // Try to dispatch to an non-editable inset near this position
1224 // via the temp cursor. If the inset wishes to change the real
1225 // cursor it has to do so explicitly by using
1226 // cur.bv().cursor() = cur; (or similar)
1228 inset->dispatch(cur, cmd);
1231 // Now dispatch to the temporary cursor. If the real cursor should
1232 // be modified, the inset's dispatch has to do so explicitly.
1233 if (!cur.result().dispatched())
1236 // Redraw if requested and necessary.
1237 if (cur.result().dispatched() && cur.result().update())
1238 return update(cur.result().update());
1244 void BufferView::scroll(int /*lines*/)
1249 // LyXText const * t = &buffer_->text();
1250 // int const line_height = defaultRowHeight();
1252 // // The new absolute coordinate
1253 // int new_top_y = top_y() + lines * line_height;
1255 // // Restrict to a valid value
1256 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1257 // new_top_y = std::max(0, new_top_y);
1259 // scrollDocView(new_top_y);
1264 void BufferView::setCursorFromRow(int row)
1269 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1272 buffer_->text().setCursor(cursor_, 0, 0);
1274 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1278 void BufferView::gotoLabel(docstring const & label)
1280 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1281 vector<docstring> labels;
1282 it->getLabelList(*buffer_, labels);
1283 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1292 TextMetrics const & BufferView::textMetrics(LyXText const * t) const
1294 return const_cast<BufferView *>(this)->textMetrics(t);
1298 TextMetrics & BufferView::textMetrics(LyXText const * t)
1300 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1301 if (tmc_it == text_metrics_.end()) {
1302 tmc_it = text_metrics_.insert(
1303 make_pair(t, TextMetrics(this, const_cast<LyXText *>(t)))).first;
1305 return tmc_it->second;
1309 ParagraphMetrics const & BufferView::parMetrics(LyXText const * t,
1312 return textMetrics(t).parMetrics(pit);
1316 int BufferView::workHeight() const
1322 void BufferView::setCursor(DocIterator const & dit)
1324 size_t const n = dit.depth();
1325 for (size_t i = 0; i < n; ++i)
1326 dit[i].inset().edit(cursor_, true);
1328 cursor_.setCursor(dit);
1329 cursor_.selection() = false;
1333 bool BufferView::checkDepm(LCursor & cur, LCursor & old)
1335 // Would be wrong to delete anything if we have a selection.
1336 if (cur.selection())
1339 bool need_anchor_change = false;
1340 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1341 need_anchor_change);
1343 if (need_anchor_change)
1349 updateLabels(*buffer_);
1351 updateMetrics(false);
1357 bool BufferView::mouseSetCursor(LCursor & cur)
1359 BOOST_ASSERT(&cur.bv() == this);
1361 // Has the cursor just left the inset?
1362 bool badcursor = false;
1363 bool leftinset = (&cursor_.inset() != &cur.inset());
1365 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1367 // do the dEPM magic if needed
1368 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1369 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1370 // the leftinset bool would not be necessary (badcursor instead).
1371 bool update = leftinset;
1372 if (!badcursor && cursor_.inTexted())
1373 update |= checkDepm(cur, cursor_);
1375 // if the cursor was in an empty script inset and the new
1376 // position is in the nucleus of the inset, notifyCursorLeaves
1377 // will kill the script inset itself. So we check all the
1378 // elements of the cursor to make sure that they are correct.
1379 // For an example, see bug 2933:
1380 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1381 // The code below could maybe be moved to a DocIterator method.
1382 //lyxerr << "cur before " << cur <<std::endl;
1383 DocIterator dit(cur.inset());
1384 dit.push_back(cur.bottom());
1386 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1387 dit.push_back(cur[i]);
1390 //lyxerr << "5 cur after" << dit <<std::endl;
1392 cursor_.setCursor(dit);
1393 cursor_.clearSelection();
1399 void BufferView::putSelectionAt(DocIterator const & cur,
1400 int length, bool backwards)
1402 cursor_.clearSelection();
1408 cursor_.pos() += length;
1409 cursor_.setSelection(cursor_, -length);
1411 cursor_.setSelection(cursor_, length);
1412 cap::saveSelection(cursor_);
1417 LCursor & BufferView::cursor()
1423 LCursor const & BufferView::cursor() const
1429 pit_type BufferView::anchor_ref() const
1435 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1437 return metrics_info_;
1441 // FIXME: We should split-up updateMetrics() for the singlepar case.
1442 void BufferView::updateMetrics(bool singlepar)
1444 LyXText & buftext = buffer_->text();
1445 TextMetrics & tm = textMetrics(&buftext);
1446 pit_type size = int(buftext.paragraphs().size());
1448 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1449 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1453 // If the paragraph metrics has changed, we can not
1454 // use the singlepar optimisation.
1456 // In Single Paragraph mode, rebreak only
1457 // the (main text, not inset!) paragraph containing the cursor.
1458 // (if this paragraph contains insets etc., rebreaking will
1459 // recursively descend)
1460 && tm.redoParagraph(cursor_.bottom().pit()))
1463 pit_type const pit = anchor_ref_;
1466 size_t const npit = buftext.paragraphs().size();
1468 // Rebreak anchor paragraph.
1470 tm.redoParagraph(pit);
1472 // Clear out the position cache in case of full screen redraw.
1474 coord_cache_.clear();
1476 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1478 // Redo paragraphs above anchor if necessary.
1480 while (y1 > 0 && pit1 > 0) {
1481 y1 -= tm.parMetrics(pit1).ascent();
1484 tm.redoParagraph(pit1);
1485 y1 -= tm.parMetrics(pit1).descent();
1489 // Take care of ascent of first line
1490 y1 -= tm.parMetrics(pit1).ascent();
1492 // Normalize anchor for next time
1496 // Grey at the beginning is ugly
1497 if (pit1 == 0 && y1 > 0) {
1503 // Redo paragraphs below the anchor if necessary.
1505 while (y2 < height_ && pit2 < int(npit) - 1) {
1506 y2 += tm.parMetrics(pit2).descent();
1509 tm.redoParagraph(pit2);
1510 y2 += tm.parMetrics(pit2).ascent();
1513 // Take care of descent of last line
1514 y2 += tm.parMetrics(pit2).descent();
1516 // The coordinates of all these paragraphs are correct, cache them
1518 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1519 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1520 ParagraphMetrics const & pm = tm.parMetrics(pit);
1522 parPos[pit] = Point(0, y);
1523 if (singlepar && pit == cursor_.bottom().pit()) {
1524 // In Single Paragraph mode, collect here the
1525 // y1 and y2 of the (one) paragraph the cursor is in
1526 y1 = y - pm.ascent();
1527 y2 = y + pm.descent();
1533 // collect cursor paragraph iter bounds
1534 pit1 = cursor_.bottom().pit();
1535 pit2 = cursor_.bottom().pit();
1538 LYXERR(Debug::DEBUG)
1539 << BOOST_CURRENT_FUNCTION
1542 << " pit1: " << pit1
1543 << " pit2: " << pit2
1544 << " npit: " << npit
1545 << " singlepar: " << singlepar
1549 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1550 singlepar? SingleParUpdate: FullScreenUpdate, size);
1552 if (lyxerr.debugging(Debug::WORKAREA)) {
1553 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1554 coord_cache_.dump();
1559 void BufferView::menuInsertLyXFile(string const & filenm)
1561 BOOST_ASSERT(cursor_.inTexted());
1562 string filename = filenm;
1564 if (filename.empty()) {
1565 // Launch a file browser
1567 string initpath = lyxrc.document_path;
1570 string const trypath = buffer_->filePath();
1571 // If directory is writeable, use this as default.
1572 if (isDirWriteable(FileName(trypath)))
1577 FileDialog fileDlg(_("Select LyX document to insert"),
1579 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1580 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support().absFilename(), "examples"))));
1582 FileDialog::Result result =
1583 fileDlg.open(from_utf8(initpath),
1584 FileFilterList(_("LyX Documents (*.lyx)")),
1587 if (result.first == FileDialog::Later)
1591 filename = to_utf8(result.second);
1593 // check selected filename
1594 if (filename.empty()) {
1595 // emit message signal.
1596 message(_("Canceled."));
1601 // Get absolute path of file and add ".lyx"
1602 // to the filename if necessary
1603 filename = fileSearch(string(), filename, "lyx").absFilename();
1605 docstring const disp_fn = makeDisplayPath(filename);
1606 // emit message signal.
1607 message(bformat(_("Inserting document %1$s..."), disp_fn));
1610 Buffer buf("", false);
1611 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1612 ErrorList & el = buffer_->errorList("Parse");
1613 // Copy the inserted document error list into the current buffer one.
1614 el = buf.errorList("Parse");
1615 recordUndo(cursor_);
1616 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1617 buf.params().textclass, el);
1618 res = _("Document %1$s inserted.");
1620 res = _("Could not insert document %1$s");
1622 // emit message signal.
1623 message(bformat(res, disp_fn));
1624 buffer_->errors("Parse");