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 par_id or pit has been changed, reset par_pit and par_id
163 // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
166 boost::tie(new_pit, new_id) = moveToPosition(bm.par_pit, bm.par_id, bm.par_pos);
167 if (bm.par_pit != new_pit || bm.par_id != new_id)
168 const_cast<BookmarksSection::Bookmark &>(bm).setPos(new_pit, new_id);
170 // current buffer is going to be switched-off, save cursor pos
171 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
172 boost::tie(cursor_.pit(), cursor_.pos()) );
175 // If we're quitting lyx, don't bother updating stuff
181 // If we are closing current buffer, switch to the first in
184 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
185 << " No Buffer!" << endl;
186 // We are closing the buffer, use the first buffer as current
187 buffer_ = theBufferList().first();
189 // Set current buffer
194 cursor_ = LCursor(*this);
199 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
200 << "Buffer addr: " << buffer_ << endl;
201 cursor_.push(buffer_->inset());
202 cursor_.resetAnchor();
203 buffer_->text().setCurrentFont(cursor_);
204 if (buffer_->getCursor().size() > 0 &&
205 buffer_->getAnchor().size() > 0)
207 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
208 cursor_.resetAnchor();
209 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
210 cursor_.setSelection();
211 // do not set selection to the new buffer because we
212 // only paste recent selection.
217 updateMetrics(false);
219 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
220 graphics::Previews::get().generateBufferPreviews(*buffer_);
224 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
226 // File already open?
227 if (theBufferList().exists(filename.absFilename())) {
228 docstring const file = makeDisplayPath(filename.absFilename(), 20);
229 docstring text = bformat(_("The document %1$s is already "
230 "loaded.\n\nDo you want to revert "
231 "to the saved version?"), file);
232 int const ret = Alert::prompt(_("Revert to saved document?"),
233 text, 0, 1, _("&Revert"), _("&Switch to document"));
236 setBuffer(theBufferList().getBuffer(filename.absFilename()));
239 // FIXME: should be LFUN_REVERT
240 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
242 // Fall through to new load. (Asger)
248 if (isFileReadable(filename)) {
249 b = theBufferList().newBuffer(filename.absFilename());
250 if (!lyx::loadLyXFile(b, filename)) {
251 theBufferList().release(b);
255 docstring text = bformat(_("The document %1$s does not yet "
256 "exist.\n\nDo you want to create "
257 "a new document?"), from_utf8(filename.absFilename()));
258 int const ret = Alert::prompt(_("Create new document?"),
259 text, 0, 1, _("&Create"), _("Cancel"));
262 b = newFile(filename.absFilename(), string(), true);
270 // Send the "errors" signal in case of parsing errors
273 // Update the labels and section numbering.
274 updateLabels(*buffer_);
275 // scroll to the position when the file was last closed
276 if (lyxrc.use_lastfilepos) {
279 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
280 // if successfully move to pit (returned par_id is not zero), update metrics and reset font
281 if (moveToPosition(pit, 0, pos).get<1>()) {
283 updateMetrics(false);
284 buffer_->text().setCurrentFont(cursor_);
289 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
295 void BufferView::resize()
300 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
302 updateMetrics(false);
307 bool BufferView::fitCursor()
309 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
310 frontend::FontMetrics const & fm =
311 theFontMetrics(cursor_.getFont());
312 int const asc = fm.maxAscent();
313 int const des = fm.maxDescent();
314 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
315 if (p.y_ - asc >= 0 && p.y_ + des < height_)
323 bool BufferView::multiParSel()
325 if (!cursor_.selection())
327 bool ret = multiparsel_cache_;
328 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
329 // Either this, or previous selection spans paragraphs
330 return ret || multiparsel_cache_;
334 bool BufferView::update(Update::flags flags)
336 // last_inset_ points to the last visited inset. This pointer may become
337 // invalid because of keyboard editing. Since all such operations
338 // causes screen update(), I reset last_inset_ to avoid such a problem.
340 // This is close to a hot-path.
341 if (lyxerr.debugging(Debug::DEBUG)) {
343 << BOOST_CURRENT_FUNCTION
344 << "[fitcursor = " << (flags & Update::FitCursor)
345 << ", forceupdate = " << (flags & Update::Force)
346 << ", singlepar = " << (flags & Update::SinglePar)
347 << "] buffer: " << buffer_ << endl;
350 // Check needed to survive LyX startup
354 if (lyxerr.debugging(Debug::WORKAREA)) {
355 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
358 // Update macro store
359 buffer_->buildMacros();
361 // Now do the first drawing step if needed. This consists on updating
362 // the CoordCache in updateMetrics().
363 // The second drawing step is done in WorkArea::redraw() if needed.
365 // Case when no explicit update is requested.
367 // no need to redraw anything.
368 metrics_info_.update_strategy = NoScreenUpdate;
372 if (flags == Update::Decoration) {
373 metrics_info_.update_strategy = DecorationUpdate;
377 if (flags == Update::FitCursor
378 || flags == (Update::Decoration | Update::FitCursor)) {
379 bool const fit_cursor = fitCursor();
380 // tell the frontend to update the screen if needed.
382 updateMetrics(false);
385 if (flags & Update::Decoration) {
386 metrics_info_.update_strategy = DecorationUpdate;
389 // no screen update is needed.
390 metrics_info_.update_strategy = NoScreenUpdate;
394 bool full_metrics = flags & Update::Force;
395 if (flags & Update::MultiParSel)
396 full_metrics |= multiParSel();
398 bool const single_par = !full_metrics;
399 updateMetrics(single_par);
401 if (flags & Update::FitCursor && fitCursor())
402 updateMetrics(false);
404 // tell the frontend to update the screen.
409 void BufferView::updateScrollbar()
412 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
413 << " no text in updateScrollbar" << endl;
414 scrollbarParameters_.reset();
418 LyXText & t = buffer_->text();
419 TextMetrics & tm = text_metrics_[&t];
421 int const parsize = int(t.paragraphs().size() - 1);
422 if (anchor_ref_ > parsize) {
423 anchor_ref_ = parsize;
427 if (lyxerr.debugging(Debug::GUI)) {
429 << BOOST_CURRENT_FUNCTION
430 << " Updating scrollbar: height: " << t.paragraphs().size()
431 << " curr par: " << cursor_.bottom().pit()
432 << " default height " << defaultRowHeight() << endl;
435 // It would be better to fix the scrollbar to understand
436 // values in [0..1] and divide everything by wh
438 // estimated average paragraph height:
442 int h = tm.parMetrics(anchor_ref_).height();
444 // Normalize anchor/offset (MV):
445 while (offset_ref_ > h && anchor_ref_ < parsize) {
448 h = tm.parMetrics(anchor_ref_).height();
450 // Look at paragraph heights on-screen
453 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
456 int const h2 = tm.parMetrics(pit).height();
462 int const hav = sumh / nh;
463 // More realistic average paragraph height
468 scrollbarParameters_.height = (parsize + 1) * wh_;
469 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
470 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
474 ScrollbarParameters const & BufferView::scrollbarParameters() const
476 return scrollbarParameters_;
480 void BufferView::scrollDocView(int value)
482 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
483 << "[ value = " << value << "]" << endl;
488 LyXText & t = buffer_->text();
489 TextMetrics & tm = text_metrics_[&t];
491 float const bar = value / float(wh_ * t.paragraphs().size());
493 anchor_ref_ = int(bar * t.paragraphs().size());
494 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
495 anchor_ref_ = int(t.paragraphs().size()) - 1;
497 tm.redoParagraph(anchor_ref_);
498 int const h = tm.parMetrics(anchor_ref_).height();
499 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
500 updateMetrics(false);
504 void BufferView::setCursorFromScrollbar()
509 LyXText & t = buffer_->text();
511 int const height = 2 * defaultRowHeight();
512 int const first = height;
513 int const last = height_ - height;
514 LCursor & cur = cursor_;
516 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
519 case bv_funcs::CUR_ABOVE:
520 // We reset the cursor because bv_funcs::status() does not
521 // work when the cursor is within mathed.
522 cur.reset(buffer_->inset());
523 t.setCursorFromCoordinates(cur, 0, first);
524 cur.clearSelection();
526 case bv_funcs::CUR_BELOW:
527 // We reset the cursor because bv_funcs::status() does not
528 // work when the cursor is within mathed.
529 cur.reset(buffer_->inset());
530 t.setCursorFromCoordinates(cur, 0, last);
531 cur.clearSelection();
533 case bv_funcs::CUR_INSIDE:
534 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
535 int const newy = min(last, max(y, first));
537 cur.reset(buffer_->inset());
538 t.setCursorFromCoordinates(cur, 0, newy);
544 Change const BufferView::getCurrentChange() const
546 if (!cursor_.selection())
547 return Change(Change::UNCHANGED);
549 DocIterator dit = cursor_.selectionBegin();
550 return dit.paragraph().lookupChange(dit.pos());
554 void BufferView::saveBookmark(unsigned int idx)
556 LyX::ref().session().bookmarks().save(
557 FileName(buffer_->fileName()),
559 cursor_.paragraph().id(),
564 // emit message signal.
565 message(_("Save bookmark"));
569 boost::tuple<pit_type, int> BufferView::moveToPosition(pit_type par_pit, int par_id, pos_type par_pos)
571 cursor_.clearSelection();
573 // if a valid par_id is given, try it first
575 ParIterator par = buffer_->getParFromID(par_id);
576 if (par != buffer_->par_iterator_end()) {
577 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
578 return boost::make_tuple(cursor_.pit(), par_id);
581 // if par_id == 0, or searching through par_id failed
582 if (static_cast<size_t>(par_pit) < buffer_->paragraphs().size()) {
583 ParIterator it = buffer_->par_iterator_begin();
584 ParIterator const end = buffer_->par_iterator_end();
585 for (; it != end; ++it)
586 if (it.pit() == par_pit) {
587 // restored pos may be bigger than it->size
588 setCursor(makeDocIterator(it, min(par_pos, it->size())));
589 return boost::make_tuple(par_pit, it->id());
593 return boost::make_tuple(pit_type(0), 0);
597 void BufferView::switchKeyMap()
599 if (!lyxrc.rtl_support)
602 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
603 if (intl_->keymap == Intl::PRIMARY)
606 if (intl_->keymap == Intl::SECONDARY)
612 int BufferView::workWidth() const
618 void BufferView::center()
620 CursorSlice & bot = cursor_.bottom();
621 TextMetrics & tm = text_metrics_[bot.text()];
622 pit_type const pit = bot.pit();
623 tm.redoParagraph(pit);
624 ParagraphMetrics const & pm = tm.parMetrics(pit);
626 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
627 + pm.ascent() - height_ / 2;
631 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
635 switch (cmd.action) {
638 flag.enabled(!buffer_->undostack().empty());
641 flag.enabled(!buffer_->redostack().empty());
643 case LFUN_FILE_INSERT:
644 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
645 case LFUN_FILE_INSERT_PLAINTEXT:
646 case LFUN_BOOKMARK_SAVE:
647 // FIXME: Actually, these LFUNS should be moved to LyXText
648 flag.enabled(cursor_.inTexted());
650 case LFUN_FONT_STATE:
651 case LFUN_LABEL_INSERT:
652 case LFUN_PARAGRAPH_GOTO:
653 // FIXME handle non-trivially
654 case LFUN_OUTLINE_UP:
655 case LFUN_OUTLINE_DOWN:
656 case LFUN_OUTLINE_IN:
657 case LFUN_OUTLINE_OUT:
659 case LFUN_REFERENCE_NEXT:
661 case LFUN_WORD_REPLACE:
664 case LFUN_MARK_TOGGLE:
665 case LFUN_SCREEN_RECENTER:
666 case LFUN_BIBTEX_DATABASE_ADD:
667 case LFUN_BIBTEX_DATABASE_DEL:
668 case LFUN_WORDS_COUNT:
669 case LFUN_NEXT_INSET_TOGGLE:
673 case LFUN_LABEL_GOTO: {
674 flag.enabled(!cmd.argument().empty()
675 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
679 case LFUN_CHANGES_TRACK:
681 flag.setOnOff(buffer_->params().trackChanges);
684 case LFUN_CHANGES_OUTPUT:
685 flag.enabled(buffer_ && LaTeXFeatures::isAvailable("dvipost"));
686 flag.setOnOff(buffer_->params().outputChanges);
689 case LFUN_CHANGES_MERGE:
690 case LFUN_CHANGE_NEXT:
691 case LFUN_ALL_CHANGES_ACCEPT:
692 case LFUN_ALL_CHANGES_REJECT:
693 // TODO: context-sensitive enabling of LFUNs
694 // In principle, these command should only be enabled if there
695 // is a change in the document. However, without proper
696 // optimizations, this will inevitably result in poor performance.
697 flag.enabled(buffer_);
700 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
701 flag.setOnOff(buffer_->params().compressed);
713 Update::flags BufferView::dispatch(FuncRequest const & cmd)
715 //lyxerr << BOOST_CURRENT_FUNCTION
716 // << [ cmd = " << cmd << "]" << endl;
718 // Make sure that the cached BufferView is correct.
719 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
720 << " action[" << cmd.action << ']'
721 << " arg[" << to_utf8(cmd.argument()) << ']'
722 << " x[" << cmd.x << ']'
723 << " y[" << cmd.y << ']'
724 << " button[" << cmd.button() << ']'
727 // FIXME: this should not be possible.
731 LCursor & cur = cursor_;
732 // Default Update flags.
733 Update::flags updateFlags = Update::Force | Update::FitCursor;
735 switch (cmd.action) {
738 cur.message(_("Undo"));
739 cur.clearSelection();
740 if (!textUndo(*this)) {
741 cur.message(_("No further undo information"));
742 updateFlags = Update::None;
748 cur.message(_("Redo"));
749 cur.clearSelection();
750 if (!textRedo(*this)) {
751 cur.message(_("No further redo information"));
752 updateFlags = Update::None;
757 case LFUN_FILE_INSERT:
759 menuInsertLyXFile(to_utf8(cmd.argument()));
762 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
764 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
767 case LFUN_FILE_INSERT_PLAINTEXT:
769 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
772 case LFUN_FONT_STATE:
773 cur.message(cur.currentState());
776 case LFUN_BOOKMARK_SAVE:
777 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
780 case LFUN_LABEL_GOTO: {
781 docstring label = cmd.argument();
784 getInsetByCode<InsetRef>(cursor_,
785 InsetBase::REF_CODE);
787 label = inset->getParam("reference");
788 // persistent=false: use temp_bookmark
798 case LFUN_PARAGRAPH_GOTO: {
799 int const id = convert<int>(to_utf8(cmd.argument()));
801 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
802 ParIterator par = b->getParFromID(id);
803 if (par == b->par_iterator_end()) {
805 << "No matching paragraph found! ["
806 << id << "]." << endl;
809 << "Paragraph " << par->id()
810 << " found in buffer `"
811 << b->fileName() << "'." << endl;
815 setCursor(makeDocIterator(par, 0));
818 // Switch to other buffer view and resend cmd
819 theLyXFunc().dispatch(FuncRequest(
820 LFUN_BUFFER_SWITCH, b->fileName()));
821 theLyXFunc().dispatch(cmd);
822 updateFlags = Update::None;
831 case LFUN_OUTLINE_UP:
832 toc::outline(toc::Up, cursor_);
833 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
834 updateLabels(*buffer_);
836 case LFUN_OUTLINE_DOWN:
837 toc::outline(toc::Down, cursor_);
838 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
839 updateLabels(*buffer_);
841 case LFUN_OUTLINE_IN:
842 toc::outline(toc::In, cursor_);
843 updateLabels(*buffer_);
845 case LFUN_OUTLINE_OUT:
846 toc::outline(toc::Out, cursor_);
847 updateLabels(*buffer_);
851 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
854 case LFUN_REFERENCE_NEXT: {
855 vector<InsetBase_code> tmp;
856 tmp.push_back(InsetBase::LABEL_CODE);
857 tmp.push_back(InsetBase::REF_CODE);
858 bv_funcs::gotoInset(this, tmp, true);
862 case LFUN_CHANGES_TRACK:
863 buffer_->params().trackChanges = !buffer_->params().trackChanges;
866 case LFUN_CHANGES_OUTPUT:
867 buffer_->params().outputChanges = !buffer_->params().outputChanges;
870 case LFUN_CHANGE_NEXT:
871 findNextChange(this);
874 case LFUN_CHANGES_MERGE:
875 if (findNextChange(this))
876 showDialog("changes");
879 case LFUN_ALL_CHANGES_ACCEPT:
880 // select complete document
881 cursor_.reset(buffer_->inset());
882 cursor_.selHandle(true);
883 buffer_->text().cursorBottom(cursor_);
884 // accept everything in a single step to support atomic undo
885 buffer_->text().acceptOrRejectChanges(cursor_, LyXText::ACCEPT);
888 case LFUN_ALL_CHANGES_REJECT:
889 // select complete document
890 cursor_.reset(buffer_->inset());
891 cursor_.selHandle(true);
892 buffer_->text().cursorBottom(cursor_);
893 // reject everything in a single step to support atomic undo
894 // Note: reject does not work recursively; the user may have to repeat the operation
895 buffer_->text().acceptOrRejectChanges(cursor_, LyXText::REJECT);
902 case LFUN_WORD_REPLACE:
907 cur.clearSelection();
909 cur.message(from_utf8(N_("Mark off")));
913 cur.clearSelection();
916 cur.message(from_utf8(N_("Mark on")));
919 case LFUN_MARK_TOGGLE:
920 cur.clearSelection();
923 cur.message(from_utf8(N_("Mark removed")));
926 cur.message(from_utf8(N_("Mark set")));
931 case LFUN_SCREEN_RECENTER:
935 case LFUN_BIBTEX_DATABASE_ADD: {
936 LCursor tmpcur = cursor_;
937 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
938 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
939 InsetBase::BIBTEX_CODE);
941 if (inset->addDatabase(to_utf8(cmd.argument())))
942 buffer_->updateBibfilesCache();
947 case LFUN_BIBTEX_DATABASE_DEL: {
948 LCursor tmpcur = cursor_;
949 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
950 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
951 InsetBase::BIBTEX_CODE);
953 if (inset->delDatabase(to_utf8(cmd.argument())))
954 buffer_->updateBibfilesCache();
959 case LFUN_WORDS_COUNT: {
960 DocIterator from, to;
961 if (cur.selection()) {
962 from = cur.selectionBegin();
963 to = cur.selectionEnd();
965 from = doc_iterator_begin(buffer_->inset());
966 to = doc_iterator_end(buffer_->inset());
968 int const count = countWords(from, to);
972 message = bformat(_("%1$d words in selection."),
975 message = bformat(_("%1$d words in document."),
980 message = _("One word in selection.");
982 message = _("One word in document.");
985 Alert::information(_("Count words"), message);
989 case LFUN_BUFFER_TOGGLE_COMPRESSION:
990 // turn compression on/off
991 buffer_->params().compressed = !buffer_->params().compressed;
994 case LFUN_NEXT_INSET_TOGGLE: {
995 // this is the real function we want to invoke
996 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
997 // if there is an inset at cursor, see whether it
999 InsetBase * inset = cur.nextInset();
1000 if (inset && inset->isActive()) {
1001 LCursor tmpcur = cur;
1002 tmpcur.pushLeft(*inset);
1003 inset->dispatch(tmpcur, tmpcmd);
1004 if (tmpcur.result().dispatched()) {
1008 // if it did not work, try the underlying inset.
1009 if (!cur.result().dispatched())
1010 cur.dispatch(tmpcmd);
1012 if (cur.result().dispatched())
1013 cur.clearSelection();
1019 updateFlags = Update::None;
1026 docstring const BufferView::requestSelection()
1031 LCursor & cur = cursor_;
1033 if (!cur.selection()) {
1034 xsel_cache_.set = false;
1038 if (!xsel_cache_.set ||
1039 cur.top() != xsel_cache_.cursor ||
1040 cur.anchor_.top() != xsel_cache_.anchor)
1042 xsel_cache_.cursor = cur.top();
1043 xsel_cache_.anchor = cur.anchor_.top();
1044 xsel_cache_.set = cur.selection();
1045 return cur.selectionAsString(false);
1051 void BufferView::clearSelection()
1054 cursor_.clearSelection();
1055 // Clear the selection buffer. Otherwise a subsequent
1056 // middle-mouse-button paste would use the selection buffer,
1057 // not the more current external selection.
1058 cap::clearSelection();
1059 xsel_cache_.set = false;
1060 // The buffer did not really change, but this causes the
1061 // redraw we need because we cleared the selection above.
1067 void BufferView::workAreaResize(int width, int height)
1069 // Update from work area
1073 // The complete text metrics will be redone.
1074 text_metrics_.clear();
1081 InsetBase const * BufferView::getCoveringInset(LyXText const & text, int x, int y)
1083 pit_type pit = text.getPitNearY(*this, y);
1084 BOOST_ASSERT(pit != -1);
1085 Paragraph const & par = text.getPar(pit);
1087 lyxerr[Debug::DEBUG]
1088 << BOOST_CURRENT_FUNCTION
1093 InsetList::const_iterator iit = par.insetlist.begin();
1094 InsetList::const_iterator iend = par.insetlist.end();
1095 for (; iit != iend; ++iit) {
1096 InsetBase * const inset = iit->inset;
1097 if (inset->covers(*this, x, y)) {
1098 if (!inset->descendable())
1099 // No need to go further down if the inset is not
1103 size_t cell_number = inset->nargs();
1104 // Check all the inner cell.
1105 for (size_t i = 0; i != cell_number; ++i) {
1106 LyXText const * inner_text = inset->getText(i);
1109 InsetBase const * inset_deeper =
1110 getCoveringInset(*inner_text, x, y);
1112 return inset_deeper;
1116 lyxerr[Debug::DEBUG]
1117 << BOOST_CURRENT_FUNCTION
1118 << ": Hit inset: " << inset << endl;
1122 lyxerr[Debug::DEBUG]
1123 << BOOST_CURRENT_FUNCTION
1124 << ": No inset hit. " << endl;
1129 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1131 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1133 // This is only called for mouse related events including
1134 // LFUN_FILE_OPEN generated by drag-and-drop.
1135 FuncRequest cmd = cmd0;
1137 // E.g. Qt mouse press when no buffer
1142 cur.push(buffer_->inset());
1143 cur.selection() = cursor_.selection();
1145 // Either the inset under the cursor or the
1146 // surrounding LyXText will handle this event.
1148 // make sure we stay within the screen...
1149 cmd.y = min(max(cmd.y, -1), height_);
1151 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1153 // Get inset under mouse, if there is one.
1154 InsetBase const * covering_inset =
1155 getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1156 if (covering_inset == last_inset_)
1157 // Same inset, no need to do anything...
1160 bool need_redraw = false;
1161 // const_cast because of setMouseHover().
1162 InsetBase * inset = const_cast<InsetBase *>(covering_inset);
1164 // Remove the hint on the last hovered inset (if any).
1165 need_redraw |= last_inset_->setMouseHover(false);
1167 // Highlighted the newly hovered inset (if any).
1168 need_redraw |= inset->setMouseHover(true);
1169 last_inset_ = inset;
1171 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1172 // not expose the button for redraw. We adjust here the metrics dimension
1173 // to enable a full redraw.
1174 // FIXME: It is possible to redraw only the area around the button!
1176 && metrics_info_.update_strategy == SingleParUpdate) {
1177 // FIXME: It should be possible to redraw only the area around
1178 // the button by doing this:
1180 //metrics_info_.singlepar = false;
1181 //metrics_info_.y1 = ymin of button;
1182 //metrics_info_.y2 = ymax of button;
1184 // Unfortunately, rowpainter.C:paintText() does not distinguish
1185 // between background updates and text updates. So we use the hammer
1186 // solution for now. We could also avoid the updateMetrics() below
1187 // by using the first and last pit of the CoordCache. Have a look
1188 // at LyXText::getPitNearY() to see what I mean.
1190 //metrics_info_.pit1 = first pit of CoordCache;
1191 //metrics_info_.pit2 = last pit of CoordCache;
1192 //metrics_info_.singlepar = false;
1193 //metrics_info_.y1 = 0;
1194 //metrics_info_.y2 = height_;
1196 updateMetrics(false);
1199 // This event (moving without mouse click) is not passed further.
1200 // This should be changed if it is further utilized.
1204 // Build temporary cursor.
1205 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1207 // Put anchor at the same position.
1210 // Try to dispatch to an non-editable inset near this position
1211 // via the temp cursor. If the inset wishes to change the real
1212 // cursor it has to do so explicitly by using
1213 // cur.bv().cursor() = cur; (or similar)
1215 inset->dispatch(cur, cmd);
1218 // Now dispatch to the temporary cursor. If the real cursor should
1219 // be modified, the inset's dispatch has to do so explicitly.
1220 if (!cur.result().dispatched())
1223 // Redraw if requested and necessary.
1224 if (cur.result().dispatched() && cur.result().update())
1225 return update(cur.result().update());
1231 void BufferView::scroll(int /*lines*/)
1236 // LyXText const * t = &buffer_->text();
1237 // int const line_height = defaultRowHeight();
1239 // // The new absolute coordinate
1240 // int new_top_y = top_y() + lines * line_height;
1242 // // Restrict to a valid value
1243 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1244 // new_top_y = std::max(0, new_top_y);
1246 // scrollDocView(new_top_y);
1251 void BufferView::setCursorFromRow(int row)
1256 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1259 buffer_->text().setCursor(cursor_, 0, 0);
1261 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1265 void BufferView::gotoLabel(docstring const & label)
1267 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1268 vector<docstring> labels;
1269 it->getLabelList(*buffer_, labels);
1270 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1279 TextMetrics const & BufferView::textMetrics(LyXText const * t) const
1281 return const_cast<BufferView *>(this)->textMetrics(t);
1285 TextMetrics & BufferView::textMetrics(LyXText const * t)
1287 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1288 if (tmc_it == text_metrics_.end()) {
1289 tmc_it = text_metrics_.insert(
1290 make_pair(t, TextMetrics(this, const_cast<LyXText *>(t)))).first;
1292 return tmc_it->second;
1296 ParagraphMetrics const & BufferView::parMetrics(LyXText const * t,
1299 return textMetrics(t).parMetrics(pit);
1303 int BufferView::workHeight() const
1309 void BufferView::setCursor(DocIterator const & dit)
1311 size_t const n = dit.depth();
1312 for (size_t i = 0; i < n; ++i)
1313 dit[i].inset().edit(cursor_, true);
1315 cursor_.setCursor(dit);
1316 cursor_.selection() = false;
1320 bool BufferView::checkDepm(LCursor & cur, LCursor & old)
1322 // Would be wrong to delete anything if we have a selection.
1323 if (cur.selection())
1326 bool need_anchor_change = false;
1327 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1328 need_anchor_change);
1330 if (need_anchor_change)
1336 updateLabels(*buffer_);
1338 updateMetrics(false);
1344 bool BufferView::mouseSetCursor(LCursor & cur)
1346 BOOST_ASSERT(&cur.bv() == this);
1348 // Has the cursor just left the inset?
1349 bool badcursor = false;
1350 if (&cursor_.inset() != &cur.inset())
1351 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1353 // do the dEPM magic if needed
1354 // FIXME: move this to InsetText::notifyCursorLeaves?
1355 bool update = false;
1356 if (!badcursor && cursor_.inTexted())
1357 checkDepm(cur, cursor_);
1359 // if the cursor was in an empty script inset and the new
1360 // position is in the nucleus of the inset, notifyCursorLeaves
1361 // will kill the script inset itself. So we check all the
1362 // elements of the cursor to make sure that they are correct.
1363 // For an example, see bug 2933:
1364 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1365 // The code below could maybe be moved to a DocIterator method.
1366 //lyxerr << "cur before " << cur <<std::endl;
1367 DocIterator dit(cur.inset());
1368 dit.push_back(cur.bottom());
1370 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1371 dit.push_back(cur[i]);
1374 //lyxerr << "5 cur after" << dit <<std::endl;
1376 cursor_.setCursor(dit);
1377 cursor_.clearSelection();
1383 void BufferView::putSelectionAt(DocIterator const & cur,
1384 int length, bool backwards)
1386 cursor_.clearSelection();
1392 cursor_.pos() += length;
1393 cursor_.setSelection(cursor_, -length);
1395 cursor_.setSelection(cursor_, length);
1396 cap::saveSelection(cursor_);
1401 LCursor & BufferView::cursor()
1407 LCursor const & BufferView::cursor() const
1413 pit_type BufferView::anchor_ref() const
1419 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1421 return metrics_info_;
1425 // FIXME: We should split-up updateMetrics() for the singlepar case.
1426 void BufferView::updateMetrics(bool singlepar)
1428 LyXText & buftext = buffer_->text();
1429 TextMetrics & tm = textMetrics(&buftext);
1430 pit_type size = int(buftext.paragraphs().size());
1432 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1433 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1437 // If the paragraph metrics has changed, we can not
1438 // use the singlepar optimisation.
1440 // In Single Paragraph mode, rebreak only
1441 // the (main text, not inset!) paragraph containing the cursor.
1442 // (if this paragraph contains insets etc., rebreaking will
1443 // recursively descend)
1444 && tm.redoParagraph(cursor_.bottom().pit()))
1447 pit_type const pit = anchor_ref_;
1450 size_t const npit = buftext.paragraphs().size();
1452 // Rebreak anchor paragraph.
1454 tm.redoParagraph(pit);
1456 // Clear out the position cache in case of full screen redraw.
1458 coord_cache_.clear();
1460 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1462 // Redo paragraphs above anchor if necessary.
1464 while (y1 > 0 && pit1 > 0) {
1465 y1 -= tm.parMetrics(pit1).ascent();
1468 tm.redoParagraph(pit1);
1469 y1 -= tm.parMetrics(pit1).descent();
1473 // Take care of ascent of first line
1474 y1 -= tm.parMetrics(pit1).ascent();
1476 // Normalize anchor for next time
1480 // Grey at the beginning is ugly
1481 if (pit1 == 0 && y1 > 0) {
1487 // Redo paragraphs below the anchor if necessary.
1489 while (y2 < height_ && pit2 < int(npit) - 1) {
1490 y2 += tm.parMetrics(pit2).descent();
1493 tm.redoParagraph(pit2);
1494 y2 += tm.parMetrics(pit2).ascent();
1497 // Take care of descent of last line
1498 y2 += tm.parMetrics(pit2).descent();
1500 // The coordinates of all these paragraphs are correct, cache them
1502 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1503 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1504 ParagraphMetrics const & pm = tm.parMetrics(pit);
1506 parPos[pit] = Point(0, y);
1507 if (singlepar && pit == cursor_.bottom().pit()) {
1508 // In Single Paragraph mode, collect here the
1509 // y1 and y2 of the (one) paragraph the cursor is in
1510 y1 = y - pm.ascent();
1511 y2 = y + pm.descent();
1517 // collect cursor paragraph iter bounds
1518 pit1 = cursor_.bottom().pit();
1519 pit2 = cursor_.bottom().pit();
1522 lyxerr[Debug::DEBUG]
1523 << BOOST_CURRENT_FUNCTION
1526 << " pit1: " << pit1
1527 << " pit2: " << pit2
1528 << " npit: " << npit
1529 << " singlepar: " << singlepar
1533 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1534 singlepar? SingleParUpdate: FullScreenUpdate, size);
1536 if (lyxerr.debugging(Debug::WORKAREA)) {
1537 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1538 coord_cache_.dump();
1543 void BufferView::menuInsertLyXFile(string const & filenm)
1545 BOOST_ASSERT(cursor_.inTexted());
1546 string filename = filenm;
1548 if (filename.empty()) {
1549 // Launch a file browser
1551 string initpath = lyxrc.document_path;
1554 string const trypath = buffer_->filePath();
1555 // If directory is writeable, use this as default.
1556 if (isDirWriteable(FileName(trypath)))
1561 FileDialog fileDlg(_("Select LyX document to insert"),
1563 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1564 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1566 FileDialog::Result result =
1567 fileDlg.open(from_utf8(initpath),
1568 FileFilterList(_("LyX Documents (*.lyx)")),
1571 if (result.first == FileDialog::Later)
1575 filename = to_utf8(result.second);
1577 // check selected filename
1578 if (filename.empty()) {
1579 // emit message signal.
1580 message(_("Canceled."));
1585 // Get absolute path of file and add ".lyx"
1586 // to the filename if necessary
1587 filename = fileSearch(string(), filename, "lyx").absFilename();
1589 docstring const disp_fn = makeDisplayPath(filename);
1590 // emit message signal.
1591 message(bformat(_("Inserting document %1$s..."), disp_fn));
1594 Buffer buf("", false);
1595 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1596 ErrorList & el = buffer_->errorList("Parse");
1597 // Copy the inserted document error list into the current buffer one.
1598 el = buf.errorList("Parse");
1599 recordUndo(cursor_);
1600 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1601 buf.params().textclass, el);
1602 res = _("Document %1$s inserted.");
1604 res = _("Could not insert document %1$s");
1606 // emit message signal.
1607 message(bformat(res, disp_fn));
1608 buffer_->errors("Parse");