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"
24 #include "CutAndPaste.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
34 #include "insetiterator.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
41 #include "lyxlayout.h"
43 #include "lyxtextclass.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
62 #include "frontends/Alert.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/FontMetrics.h"
66 #include "graphics/Previews.h"
68 #include "support/convert.h"
69 #include "support/filefilterlist.h"
70 #include "support/filetools.h"
71 #include "support/package.h"
72 #include "support/types.h"
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
83 using support::addPath;
84 using support::bformat;
85 using support::FileFilterList;
86 using support::fileSearch;
87 using support::isDirWriteable;
88 using support::makeDisplayPath;
89 using support::makeAbsPath;
90 using support::package;
94 using std::istringstream;
98 using std::mem_fun_ref;
102 namespace Alert = frontend::Alert;
106 /// Return an inset of this class if it exists at the current cursor position
108 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
111 DocIterator it = cur;
112 if (it.nextInset() &&
113 it.nextInset()->lyxCode() == code) {
114 inset = static_cast<T*>(it.nextInset());
122 BufferView::BufferView()
123 : width_(0), height_(0), buffer_(0), wh_(0),
125 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 xsel_cache_.set = false;
129 intl_->initKeyMapper(lyxrc.use_kbmap);
133 BufferView::~BufferView()
138 Buffer * BufferView::buffer() const
144 void BufferView::setBuffer(Buffer * b)
146 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
147 << "[ b = " << b << "]" << endl;
150 // Save the actual cursor position and anchor inside the
151 // buffer so that it can be restored in case we rechange
152 // to this buffer later on.
153 buffer_->saveCursor(cursor_.selectionBegin(),
154 cursor_.selectionEnd());
155 // current buffer is going to be switched-off, save cursor pos
156 LyX::ref().session().lastFilePos().save(buffer_->fileName(),
157 boost::tie(cursor_.pit(), cursor_.pos()) );
160 // If we're quitting lyx, don't bother updating stuff
166 // If we are closing current buffer, switch to the first in
169 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
170 << " No Buffer!" << endl;
171 // We are closing the buffer, use the first buffer as current
172 buffer_ = theBufferList().first();
174 // Set current buffer
179 cursor_ = LCursor(*this);
184 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
185 << "Buffer addr: " << buffer_ << endl;
186 cursor_.push(buffer_->inset());
187 cursor_.resetAnchor();
188 buffer_->text().init(this);
189 buffer_->text().setCurrentFont(cursor_);
190 if (buffer_->getCursor().size() > 0 &&
191 buffer_->getAnchor().size() > 0)
193 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
194 cursor_.resetAnchor();
195 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
196 cursor_.setSelection();
202 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
203 graphics::Previews::get().generateBufferPreviews(*buffer_);
207 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
209 // Get absolute path of file and add ".lyx"
210 // to the filename if necessary
211 string s = fileSearch(string(), filename, "lyx");
213 bool const found = !s.empty();
218 // File already open?
219 if (theBufferList().exists(s)) {
220 docstring const file = makeDisplayPath(s, 20);
221 docstring text = bformat(_("The document %1$s is already "
222 "loaded.\n\nDo you want to revert "
223 "to the saved version?"), file);
224 int const ret = Alert::prompt(_("Revert to saved document?"),
225 text, 0, 1, _("&Revert"), _("&Switch to document"));
228 setBuffer(theBufferList().getBuffer(s));
231 // FIXME: should be LFUN_REVERT
232 if (!theBufferList().close(theBufferList().getBuffer(s), false))
234 // Fall through to new load. (Asger)
241 b = theBufferList().newBuffer(s);
242 if (!lyx::loadLyXFile(b, s)) {
243 theBufferList().release(b);
247 docstring text = bformat(_("The document %1$s does not yet "
248 "exist.\n\nDo you want to create "
249 "a new document?"), from_utf8(s));
250 int const ret = Alert::prompt(_("Create new document?"),
251 text, 0, 1, _("&Create"), _("Cancel"));
254 b = newFile(s, string(), true);
262 // Send the "errors" signal in case of parsing errors
265 // scroll to the position when the file was last closed
266 if (lyxrc.use_lastfilepos) {
269 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(s);
270 // I am not sure how to separate the following part to a function
271 // so I will leave this to Lars.
273 // check pit since the document may be externally changed.
274 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
275 ParIterator it = b->par_iterator_begin();
276 ParIterator const end = b->par_iterator_end();
277 for (; it != end; ++it)
278 if (it.pit() == pit) {
279 // restored pos may be bigger than it->size
280 setCursor(makeDocIterator(it, min(pos, it->size())));
281 update(Update::FitCursor);
288 LyX::ref().session().lastFiles().add(b->fileName());
294 void BufferView::reload()
296 string const fn = buffer_->fileName();
297 if (theBufferList().close(buffer_, false))
302 void BufferView::resize()
307 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
309 buffer_->text().init(this);
315 bool BufferView::fitCursor()
317 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
318 frontend::FontMetrics const & fm =
319 theFontMetrics(cursor_.getFont());
320 int const asc = fm.maxAscent();
321 int const des = fm.maxDescent();
322 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
323 if (p.y_ - asc >= 0 && p.y_ + des < height_)
331 bool BufferView::multiParSel()
333 if (!cursor_.selection())
335 bool ret = multiparsel_cache_;
336 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
337 // Either this, or previous selection spans paragraphs
338 return ret || multiparsel_cache_;
342 std::pair<bool, bool> BufferView::update(Update::flags flags)
344 // This is close to a hot-path.
345 if (lyxerr.debugging(Debug::DEBUG)) {
347 << BOOST_CURRENT_FUNCTION
348 << "[fitcursor = " << (flags & Update::FitCursor)
349 << ", forceupdate = " << (flags & Update::Force)
350 << ", singlepar = " << (flags & Update::SinglePar)
351 << "] buffer: " << buffer_ << endl;
354 // Check needed to survive LyX startup
356 return make_pair(false, false);
358 if (lyxerr.debugging(Debug::WORKAREA)) {
359 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
362 // Update macro store
363 buffer_->buildMacros();
365 // Now do the first drawing step if needed. This consists on updating
366 // the CoordCache in updateMetrics().
367 // The second drawing step is done in WorkArea::redraw() if needed.
369 // Case when no explicit update is requested.
370 if (!(flags & (Update::SinglePar | Update::Force))) {
371 if (fitCursor() || multiParSel()) {
372 // a CoordCache update is needed
373 updateMetrics(false);
374 // tell the frontend to update the screen.
375 return make_pair(true, false);
377 // no need to do anything.
378 return make_pair(false, false);
381 // We are now in the case (Update::SinglePar | Update::Force)
382 bool single_par = flags & Update::SinglePar;
383 updateMetrics(single_par);
385 // Don't forget to do check for fitCursor() and multiParSel().
389 return make_pair(true, single_par);
393 void BufferView::updateScrollbar()
396 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
397 << " no text in updateScrollbar" << endl;
398 scrollbarParameters_.reset();
402 LyXText & t = buffer_->text();
403 int const parsize = int(t.paragraphs().size() - 1);
404 if (anchor_ref_ > parsize) {
405 anchor_ref_ = parsize;
409 if (lyxerr.debugging(Debug::GUI)) {
411 << BOOST_CURRENT_FUNCTION
412 << " Updating scrollbar: height: " << t.paragraphs().size()
413 << " curr par: " << cursor_.bottom().pit()
414 << " default height " << defaultRowHeight() << endl;
417 // It would be better to fix the scrollbar to understand
418 // values in [0..1] and divide everything by wh
420 // estimated average paragraph height:
423 int h = t.getPar(anchor_ref_).height();
425 // Normalize anchor/offset (MV):
426 while (offset_ref_ > h && anchor_ref_ < parsize) {
429 h = t.getPar(anchor_ref_).height();
431 // Look at paragraph heights on-screen
434 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
437 int const h2 = t.getPar(pit).height();
443 int const hav = sumh / nh;
444 // More realistic average paragraph height
449 scrollbarParameters_.height = (parsize + 1) * wh_;
450 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
451 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
455 ScrollbarParameters const & BufferView::scrollbarParameters() const
457 return scrollbarParameters_;
461 void BufferView::scrollDocView(int value)
463 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
464 << "[ value = " << value << "]" << endl;
469 LyXText & t = buffer_->text();
471 float const bar = value / float(wh_ * t.paragraphs().size());
473 anchor_ref_ = int(bar * t.paragraphs().size());
474 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
475 anchor_ref_ = int(t.paragraphs().size()) - 1;
476 t.redoParagraph(*this, anchor_ref_);
477 int const h = t.getPar(anchor_ref_).height();
478 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
482 void BufferView::setCursorFromScrollbar()
484 LyXText & t = buffer_->text();
486 int const height = 2 * defaultRowHeight();
487 int const first = height;
488 int const last = height_ - height;
489 LCursor & cur = cursor_;
491 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
494 case bv_funcs::CUR_ABOVE:
495 t.setCursorFromCoordinates(cur, 0, first);
496 cur.clearSelection();
498 case bv_funcs::CUR_BELOW:
499 t.setCursorFromCoordinates(cur, 0, last);
500 cur.clearSelection();
502 case bv_funcs::CUR_INSIDE:
503 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
504 int const newy = min(last, max(y, first));
506 cur.reset(buffer_->inset());
507 t.setCursorFromCoordinates(cur, 0, newy);
513 Change const BufferView::getCurrentChange() const
515 if (!cursor_.selection())
516 return Change(Change::UNCHANGED);
518 DocIterator dit = cursor_.selectionBegin();
519 return dit.paragraph().lookupChange(dit.pos());
523 void BufferView::saveBookmark(bool persistent)
525 LyX::ref().session().bookmarks().save(
527 cursor_.paragraph().id(),
532 // emit message signal.
533 message(_("Save bookmark"));
537 void BufferView::moveToPosition(int par_id, pos_type par_pos)
539 cursor_.clearSelection();
541 ParIterator par = buffer_->getParFromID(par_id);
542 if (par == buffer_->par_iterator_end())
545 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
549 void BufferView::switchKeyMap()
551 if (!lyxrc.rtl_support)
554 if (getLyXText()->real_current_font.isRightToLeft()) {
555 if (intl_->keymap == Intl::PRIMARY)
558 if (intl_->keymap == Intl::SECONDARY)
564 int BufferView::workWidth() const
570 void BufferView::center()
572 CursorSlice & bot = cursor_.bottom();
573 pit_type const pit = bot.pit();
574 bot.text()->redoParagraph(*this, pit);
575 Paragraph const & par = bot.text()->paragraphs()[pit];
577 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
578 + par.ascent() - height_ / 2;
582 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
586 switch (cmd.action) {
589 flag.enabled(!buffer_->undostack().empty());
592 flag.enabled(!buffer_->redostack().empty());
594 case LFUN_FILE_INSERT:
595 case LFUN_FILE_INSERT_ASCII_PARA:
596 case LFUN_FILE_INSERT_ASCII:
597 case LFUN_BOOKMARK_SAVE:
598 // FIXME: Actually, these LFUNS should be moved to LyXText
599 flag.enabled(cursor_.inTexted());
601 case LFUN_FONT_STATE:
602 case LFUN_LABEL_INSERT:
603 case LFUN_PARAGRAPH_GOTO:
604 // FIXME handle non-trivially
605 case LFUN_OUTLINE_UP:
606 case LFUN_OUTLINE_DOWN:
607 case LFUN_OUTLINE_IN:
608 case LFUN_OUTLINE_OUT:
610 case LFUN_REFERENCE_NEXT:
612 case LFUN_WORD_REPLACE:
615 case LFUN_MARK_TOGGLE:
616 case LFUN_SCREEN_RECENTER:
617 case LFUN_BIBTEX_DATABASE_ADD:
618 case LFUN_BIBTEX_DATABASE_DEL:
619 case LFUN_WORDS_COUNT:
620 case LFUN_NEXT_INSET_TOGGLE:
624 case LFUN_LABEL_GOTO: {
625 flag.enabled(!cmd.argument().empty()
626 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
630 case LFUN_CHANGES_TRACK:
632 flag.setOnOff(buffer_->params().trackChanges);
635 case LFUN_CHANGES_OUTPUT: {
636 OutputParams runparams;
637 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
638 flag.enabled(buffer_ && features.isAvailable("dvipost"));
639 flag.setOnOff(buffer_->params().outputChanges);
643 case LFUN_CHANGES_MERGE:
644 case LFUN_CHANGE_NEXT:
645 case LFUN_ALL_CHANGES_ACCEPT:
646 case LFUN_ALL_CHANGES_REJECT:
647 flag.enabled(buffer_); // FIXME: Change tracking (MG)
650 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
651 flag.setOnOff(buffer_->params().compressed);
663 bool BufferView::dispatch(FuncRequest const & cmd)
665 //lyxerr << BOOST_CURRENT_FUNCTION
666 // << [ cmd = " << cmd << "]" << endl;
668 // Make sure that the cached BufferView is correct.
669 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
670 << " action[" << cmd.action << ']'
671 << " arg[" << to_utf8(cmd.argument()) << ']'
672 << " x[" << cmd.x << ']'
673 << " y[" << cmd.y << ']'
674 << " button[" << cmd.button() << ']'
677 LCursor & cur = cursor_;
679 switch (cmd.action) {
683 cur.message(_("Undo"));
684 cur.clearSelection();
685 if (!textUndo(*this))
686 cur.message(_("No further undo information"));
694 cur.message(_("Redo"));
695 cur.clearSelection();
696 if (!textRedo(*this))
697 cur.message(_("No further redo information"));
703 case LFUN_FILE_INSERT:
704 // FIXME: We don't know the encoding of filenames
705 menuInsertLyXFile(to_utf8(cmd.argument()));
708 case LFUN_FILE_INSERT_ASCII_PARA:
709 // FIXME: We don't know the encoding of filenames
710 insertAsciiFile(this, to_utf8(cmd.argument()), true);
713 case LFUN_FILE_INSERT_ASCII:
714 // FIXME: We don't know the encoding of filenames
715 insertAsciiFile(this, to_utf8(cmd.argument()), false);
718 case LFUN_FONT_STATE:
719 cur.message(from_utf8(cur.currentState()));
722 case LFUN_BOOKMARK_SAVE:
723 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
726 case LFUN_LABEL_GOTO: {
727 docstring label = cmd.argument();
730 getInsetByCode<InsetRef>(cursor_,
731 InsetBase::REF_CODE);
733 label = inset->getParam("reference");
734 // persistent=false: use temp_bookmark
744 case LFUN_PARAGRAPH_GOTO: {
745 int const id = convert<int>(to_utf8(cmd.argument()));
747 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
748 ParIterator par = b->getParFromID(id);
749 if (par == b->par_iterator_end()) {
751 << "No matching paragraph found! ["
752 << id << "]." << endl;
755 << "Paragraph " << par->id()
756 << " found in buffer `"
757 << b->fileName() << "'." << endl;
761 setCursor(makeDocIterator(par, 0));
765 // Switch to other buffer view and resend cmd
766 theLyXFunc().dispatch(FuncRequest(
767 LFUN_BUFFER_SWITCH, b->fileName()));
768 theLyXFunc().dispatch(cmd);
777 case LFUN_OUTLINE_UP:
778 toc::outline(toc::Up, cursor_);
779 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
780 updateLabels(*buffer_);
782 case LFUN_OUTLINE_DOWN:
783 toc::outline(toc::Down, cursor_);
784 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
785 updateLabels(*buffer_);
787 case LFUN_OUTLINE_IN:
788 toc::outline(toc::In, cursor_);
789 updateLabels(*buffer_);
791 case LFUN_OUTLINE_OUT:
792 toc::outline(toc::Out, cursor_);
793 updateLabels(*buffer_);
797 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
800 case LFUN_REFERENCE_NEXT: {
801 vector<InsetBase_code> tmp;
802 tmp.push_back(InsetBase::LABEL_CODE);
803 tmp.push_back(InsetBase::REF_CODE);
804 bv_funcs::gotoInset(this, tmp, true);
808 case LFUN_CHANGES_TRACK:
809 buffer_->params().trackChanges = !buffer_->params().trackChanges;
812 case LFUN_CHANGES_OUTPUT: {
813 buffer_->params().outputChanges = !buffer_->params().outputChanges;
817 case LFUN_CHANGE_NEXT:
818 findNextChange(this);
821 case LFUN_CHANGES_MERGE:
822 if (findNextChange(this))
823 showDialog("changes");
826 case LFUN_ALL_CHANGES_ACCEPT: {
827 cursor_.reset(buffer_->inset());
829 #warning FIXME changes
831 while (findNextChange(this))
832 getLyXText()->acceptChange(cursor_);
837 case LFUN_ALL_CHANGES_REJECT: {
838 cursor_.reset(buffer_->inset());
840 #warning FIXME changes
842 while (findNextChange(this))
843 getLyXText()->rejectChange(cursor_);
851 case LFUN_WORD_REPLACE:
856 cur.clearSelection();
858 cur.message(from_utf8(N_("Mark off")));
862 cur.clearSelection();
865 cur.message(from_utf8(N_("Mark on")));
868 case LFUN_MARK_TOGGLE:
869 cur.clearSelection();
872 cur.message(from_utf8(N_("Mark removed")));
875 cur.message(from_utf8(N_("Mark set")));
880 case LFUN_SCREEN_RECENTER:
884 case LFUN_BIBTEX_DATABASE_ADD: {
885 LCursor tmpcur = cursor_;
886 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
887 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
888 InsetBase::BIBTEX_CODE);
890 if (inset->addDatabase(to_utf8(cmd.argument())))
891 buffer_->updateBibfilesCache();
896 case LFUN_BIBTEX_DATABASE_DEL: {
897 LCursor tmpcur = cursor_;
898 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
899 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
900 InsetBase::BIBTEX_CODE);
902 if (inset->delDatabase(to_utf8(cmd.argument())))
903 buffer_->updateBibfilesCache();
908 case LFUN_WORDS_COUNT: {
909 DocIterator from, to;
910 if (cur.selection()) {
911 from = cur.selectionBegin();
912 to = cur.selectionEnd();
914 from = doc_iterator_begin(buffer_->inset());
915 to = doc_iterator_end(buffer_->inset());
917 int const count = countWords(from, to);
921 message = bformat(_("%1$d words in selection."),
924 message = bformat(_("%1$d words in document."),
929 message = _("One word in selection.");
931 message = _("One word in document.");
934 Alert::information(_("Count words"), message);
938 case LFUN_BUFFER_TOGGLE_COMPRESSION:
939 // turn compression on/off
940 buffer_->params().compressed = !buffer_->params().compressed;
943 case LFUN_NEXT_INSET_TOGGLE: {
944 // this is the real function we want to invoke
945 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
946 // if there is an inset at cursor, see whether it
948 InsetBase * inset = cur.nextInset();
949 if (inset && inset->isActive()) {
950 LCursor tmpcur = cur;
951 tmpcur.pushLeft(*inset);
952 inset->dispatch(tmpcur, tmpcmd);
953 if (tmpcur.result().dispatched()) {
957 // if it did not work, try the underlying inset.
958 if (!cur.result().dispatched())
959 cur.dispatch(tmpcmd);
961 if (cur.result().dispatched())
962 cur.clearSelection();
975 docstring const BufferView::requestSelection()
980 LCursor & cur = cursor_;
982 if (!cur.selection()) {
983 xsel_cache_.set = false;
987 if (!xsel_cache_.set ||
988 cur.top() != xsel_cache_.cursor ||
989 cur.anchor_.top() != xsel_cache_.anchor)
991 xsel_cache_.cursor = cur.top();
992 xsel_cache_.anchor = cur.anchor_.top();
993 xsel_cache_.set = cur.selection();
994 return cur.selectionAsString(false);
1000 void BufferView::clearSelection()
1003 cursor_.clearSelection();
1004 xsel_cache_.set = false;
1009 void BufferView::workAreaResize(int width, int height)
1011 bool const widthChange = width != width_;
1012 bool const heightChange = height != height_;
1014 // Update from work area
1025 std::pair<bool, bool> BufferView::workAreaDispatch(FuncRequest const & cmd0)
1027 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1029 // This is only called for mouse related events including
1030 // LFUN_FILE_OPEN generated by drag-and-drop.
1031 FuncRequest cmd = cmd0;
1033 // E.g. Qt mouse press when no buffer
1035 return make_pair(false, false);
1038 cur.push(buffer_->inset());
1039 cur.selection() = cursor_.selection();
1041 // Either the inset under the cursor or the
1042 // surrounding LyXText will handle this event.
1044 // Build temporary cursor.
1045 cmd.y = min(max(cmd.y, -1), height_);
1046 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1048 //lyxerr << BOOST_CURRENT_FUNCTION
1049 // << " * hit inset at tip: " << inset << endl;
1050 //lyxerr << BOOST_CURRENT_FUNCTION
1051 // << " * created temp cursor:" << cur << endl;
1053 // Put anchor at the same position.
1056 // Try to dispatch to an non-editable inset near this position
1057 // via the temp cursor. If the inset wishes to change the real
1058 // cursor it has to do so explicitly by using
1059 // cur.bv().cursor() = cur; (or similar)
1061 inset->dispatch(cur, cmd);
1064 // Now dispatch to the temporary cursor. If the real cursor should
1065 // be modified, the inset's dispatch has to do so explicitly.
1066 if (!cur.result().dispatched())
1069 // Redraw if requested and necessary.
1070 if (cur.result().dispatched() && cur.result().update())
1071 return update(cur.result().update());
1073 // When the above and the inner function are fixed, we can do this:
1074 return make_pair(false, false);
1078 void BufferView::scroll(int /*lines*/)
1083 // LyXText const * t = &buffer_->text();
1084 // int const line_height = defaultRowHeight();
1086 // // The new absolute coordinate
1087 // int new_top_y = top_y() + lines * line_height;
1089 // // Restrict to a valid value
1090 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1091 // new_top_y = std::max(0, new_top_y);
1093 // scrollDocView(new_top_y);
1095 // // Update the scrollbar.
1096 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1100 void BufferView::setCursorFromRow(int row)
1105 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1108 buffer_->text().setCursor(cursor_, 0, 0);
1110 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1114 void BufferView::gotoLabel(docstring const & label)
1116 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1117 vector<docstring> labels;
1118 it->getLabelList(*buffer_, labels);
1119 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1128 LyXText * BufferView::getLyXText()
1130 LyXText * text = cursor_.innerText();
1136 LyXText const * BufferView::getLyXText() const
1138 LyXText const * text = cursor_.innerText();
1144 int BufferView::workHeight() const
1150 void BufferView::setCursor(DocIterator const & dit)
1152 size_t const n = dit.depth();
1153 for (size_t i = 0; i < n; ++i)
1154 dit[i].inset().edit(cursor_, true);
1156 cursor_.setCursor(dit);
1157 cursor_.selection() = false;
1161 void BufferView::mouseSetCursor(LCursor & cur)
1163 BOOST_ASSERT(&cur.bv() == this);
1165 // Has the cursor just left the inset?
1166 bool badcursor = false;
1167 if (&cursor_.inset() != &cur.inset())
1168 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1170 // do the dEPM magic if needed
1171 // FIXME: move this to InsetText::notifyCursorLeaves?
1172 if (!badcursor && cursor_.inTexted())
1173 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1176 cursor_.clearSelection();
1177 cursor_.setTargetX();
1183 void BufferView::putSelectionAt(DocIterator const & cur,
1184 int length, bool backwards)
1186 cursor_.clearSelection();
1192 cursor_.pos() += length;
1193 cursor_.setSelection(cursor_, -length);
1195 cursor_.setSelection(cursor_, length);
1200 LCursor & BufferView::cursor()
1206 LCursor const & BufferView::cursor() const
1212 pit_type BufferView::anchor_ref() const
1218 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1220 return metrics_info_;
1224 void BufferView::updateMetrics(bool singlepar)
1226 // Clear out the position cache in case of full screen redraw.
1228 coord_cache_.clear();
1230 LyXText & buftext = buffer_->text();
1231 pit_type size = int(buftext.paragraphs().size());
1233 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1234 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1238 pit_type const pit = anchor_ref_;
1241 size_t const npit = buftext.paragraphs().size();
1243 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1244 // the (main text, not inset!) paragraph containing the cursor.
1245 // (if this paragraph contains insets etc., rebreaking will
1246 // recursively descend)
1247 if (!singlepar || pit == cursor_.bottom().pit())
1248 buftext.redoParagraph(*this, pit);
1249 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1251 // Redo paragraphs above anchor if necessary; again, in Single Par
1252 // mode, only if we encounter the (main text) one having the cursor.
1254 while (y1 > 0 && pit1 > 0) {
1255 y1 -= buftext.getPar(pit1).ascent();
1257 if (!singlepar || pit1 == cursor_.bottom().pit())
1258 buftext.redoParagraph(*this, pit1);
1259 y1 -= buftext.getPar(pit1).descent();
1263 // Take care of ascent of first line
1264 y1 -= buftext.getPar(pit1).ascent();
1266 // Normalize anchor for next time
1270 // Grey at the beginning is ugly
1271 if (pit1 == 0 && y1 > 0) {
1277 // Redo paragraphs below the anchor if necessary. Single par mode:
1278 // only the one containing the cursor if encountered.
1280 while (y2 < height_ && pit2 < int(npit) - 1) {
1281 y2 += buftext.getPar(pit2).descent();
1283 if (!singlepar || pit2 == cursor_.bottom().pit())
1284 buftext.redoParagraph(*this, pit2);
1285 y2 += buftext.getPar(pit2).ascent();
1288 // Take care of descent of last line
1289 y2 += buftext.getPar(pit2).descent();
1291 // The coordinates of all these paragraphs are correct, cache them
1293 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1294 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1295 Paragraph const & par = buftext.getPar(pit);
1297 parPos[pit] = Point(0, y);
1298 if (singlepar && pit == cursor_.bottom().pit()) {
1299 // In Single Paragraph mode, collect here the
1300 // y1 and y2 of the (one) paragraph the cursor is in
1301 y1 = y - par.ascent();
1302 y2 = y + par.descent();
1308 // collect cursor paragraph iter bounds
1309 pit1 = cursor_.bottom().pit();
1310 pit2 = cursor_.bottom().pit();
1313 lyxerr[Debug::DEBUG]
1314 << BOOST_CURRENT_FUNCTION
1317 << " pit1: " << pit1
1318 << " pit2: " << pit2
1319 << " npit: " << npit
1320 << " singlepar: " << singlepar
1324 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1326 if (lyxerr.debugging(Debug::WORKAREA)) {
1327 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1328 coord_cache_.dump();
1333 void BufferView::menuInsertLyXFile(string const & filenm)
1335 BOOST_ASSERT(cursor_.inTexted());
1336 string filename = filenm;
1338 if (filename.empty()) {
1339 // Launch a file browser
1341 string initpath = lyxrc.document_path;
1344 string const trypath = buffer_->filePath();
1345 // If directory is writeable, use this as default.
1346 if (isDirWriteable(trypath))
1351 FileDialog fileDlg(_("Select LyX document to insert"),
1353 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1354 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1356 FileDialog::Result result =
1357 fileDlg.open(from_utf8(initpath),
1358 FileFilterList(_("LyX Documents (*.lyx)")),
1361 if (result.first == FileDialog::Later)
1365 filename = to_utf8(result.second);
1367 // check selected filename
1368 if (filename.empty()) {
1369 // emit message signal.
1370 message(_("Canceled."));
1375 // Get absolute path of file and add ".lyx"
1376 // to the filename if necessary
1377 filename = fileSearch(string(), filename, "lyx");
1379 docstring const disp_fn = makeDisplayPath(filename);
1380 // emit message signal.
1381 message(bformat(_("Inserting document %1$s..."), disp_fn));
1384 Buffer buf("", false);
1385 if (lyx::loadLyXFile(&buf, makeAbsPath(filename))) {
1386 ErrorList & el = buffer_->errorList("Parse");
1387 // Copy the inserted document error list into the current buffer one.
1388 el = buf.errorList("Parse");
1389 recordUndo(cursor_);
1390 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1391 buf.params().textclass, el);
1392 res = _("Document %1$s inserted.");
1394 res = _("Could not insert document %1$s");
1396 // emit message signal.
1397 message(bformat(res, disp_fn));
1398 buffer_->errors("Parse");