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/Clipboard.h"
64 #include "frontends/Dialogs.h"
65 #include "frontends/FileDialog.h"
66 #include "frontends/font_metrics.h"
67 #include "frontends/Gui.h"
68 #include "frontends/LyXView.h"
69 #include "frontends/Selection.h"
71 #include "graphics/Previews.h"
73 #include "support/convert.h"
74 #include "support/filefilterlist.h"
75 #include "support/filetools.h"
76 #include "support/package.h"
77 #include "support/types.h"
79 #include <boost/bind.hpp>
80 #include <boost/current_function.hpp>
86 using lyx::frontend::Clipboard;
87 using lyx::frontend::Gui;
92 using lyx::support::addPath;
93 using lyx::support::bformat;
94 using lyx::support::FileFilterList;
95 using lyx::support::fileSearch;
96 using lyx::support::isDirWriteable;
97 using lyx::support::makeDisplayPath;
98 using lyx::support::makeAbsPath;
99 using lyx::support::package;
103 using std::istringstream;
105 using std::make_pair;
108 using std::mem_fun_ref;
112 extern BufferList bufferlist;
117 unsigned int const saved_positions_num = 20;
120 /// Return an inset of this class if it exists at the current cursor position
122 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
125 DocIterator it = cur;
126 if (it.nextInset() &&
127 it.nextInset()->lyxCode() == code) {
128 inset = static_cast<T*>(it.nextInset());
136 BufferView::BufferView(LyXView * owner)
137 : owner_(owner), buffer_(0), wh_(0),
139 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0)
141 xsel_cache_.set = false;
143 saved_positions.resize(saved_positions_num);
144 // load saved bookmarks
145 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
146 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
147 bm != bmList.end(); ++bm)
148 if (bm->get<0>() < saved_positions_num)
149 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
150 // and then clear them
155 BufferView::~BufferView()
160 void BufferView::unsetXSel()
162 xsel_cache_.set = false;
166 Buffer * BufferView::buffer() const
172 LyXView * BufferView::owner() const
178 void BufferView::setBuffer(Buffer * b)
180 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
181 << "[ b = " << b << "]" << endl;
184 // Save the actual cursor position and anchor inside the
185 // buffer so that it can be restored in case we rechange
186 // to this buffer later on.
187 buffer_->saveCursor(cursor_.selectionBegin(),
188 cursor_.selectionEnd());
189 // current buffer is going to be switched-off, save cursor pos
190 LyX::ref().session().saveFilePosition(buffer_->fileName(),
191 boost::tie(cursor_.pit(), cursor_.pos()) );
194 // If we're quitting lyx, don't bother updating stuff
200 // If we are closing current buffer, switch to the first in
203 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
204 << " No Buffer!" << endl;
205 // We are closing the buffer, use the first buffer as current
206 buffer_ = bufferlist.first();
208 // Set current buffer
213 cursor_ = LCursor(*this);
218 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
219 << "Buffer addr: " << buffer_ << endl;
220 cursor_.push(buffer_->inset());
221 cursor_.resetAnchor();
222 buffer_->text().init(this);
223 buffer_->text().setCurrentFont(cursor_);
224 if (buffer_->getCursor().size() > 0 &&
225 buffer_->getAnchor().size() > 0)
227 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
228 cursor_.resetAnchor();
229 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
230 cursor_.setSelection();
236 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
237 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
241 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
243 // Get absolute path of file and add ".lyx"
244 // to the filename if necessary
245 string s = fileSearch(string(), filename, "lyx");
247 bool const found = !s.empty();
252 // File already open?
253 if (bufferlist.exists(s)) {
254 docstring const file = makeDisplayPath(s, 20);
255 docstring text = bformat(_("The document %1$s is already "
256 "loaded.\n\nDo you want to revert "
257 "to the saved version?"), file);
258 int const ret = Alert::prompt(_("Revert to saved document?"),
259 text, 0, 1, _("&Revert"), _("&Switch to document"));
262 setBuffer(bufferlist.getBuffer(s));
265 // FIXME: should be LFUN_REVERT
266 if (!bufferlist.close(bufferlist.getBuffer(s), false))
268 // Fall through to new load. (Asger)
274 b = bufferlist.newBuffer(s);
275 if (!::loadLyXFile(b, s)) {
276 bufferlist.release(b);
280 docstring text = bformat(_("The document %1$s does not yet "
281 "exist.\n\nDo you want to create "
282 "a new document?"), lyx::from_utf8(s));
283 int const ret = Alert::prompt(_("Create new document?"),
284 text, 0, 1, _("&Create"), _("Cancel"));
287 b = newFile(s, string(), true);
295 // Send the "errors" signal in case of parsing errors
298 // scroll to the position when the file was last closed
299 if (lyxrc.use_lastfilepos) {
302 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
303 // I am not sure how to separate the following part to a function
304 // so I will leave this to Lars.
306 // check pit since the document may be externally changed.
307 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
308 ParIterator it = b->par_iterator_begin();
309 ParIterator const end = b->par_iterator_end();
310 for (; it != end; ++it)
311 if (it.pit() == pit) {
312 // restored pos may be bigger than it->size
313 setCursor(makeDocIterator(it, min(pos, it->size())));
314 update(Update::FitCursor);
321 LyX::ref().session().addLastFile(b->fileName());
327 void BufferView::reload()
329 string const fn = buffer_->fileName();
330 if (bufferlist.close(buffer_, false))
335 void BufferView::resize()
340 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
342 buffer_->text().init(this);
348 bool BufferView::fitCursor()
350 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
351 LyXFont const font = cursor_.getFont();
352 int const asc = font_metrics::maxAscent(font);
353 int const des = font_metrics::maxDescent(font);
354 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
355 if (p.y_ - asc >= 0 && p.y_ + des < height_)
363 bool BufferView::multiParSel()
365 if (!cursor_.selection())
367 bool ret = multiparsel_cache_;
368 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
369 // Either this, or previous selection spans paragraphs
370 return ret || multiparsel_cache_;
374 bool BufferView::update(Update::flags flags)
376 // This is close to a hot-path.
377 if (lyxerr.debugging(Debug::DEBUG)) {
379 << BOOST_CURRENT_FUNCTION
380 << "[fitcursor = " << (flags & Update::FitCursor)
381 << ", forceupdate = " << (flags & Update::Force)
382 << ", singlepar = " << (flags & Update::SinglePar)
383 << "] buffer: " << buffer_ << endl;
386 // Check needed to survive LyX startup
390 // Update macro store
391 buffer_->buildMacros();
393 // First drawing step
394 updateMetrics(flags & Update::SinglePar);
396 // The second drawing step is done in WorkArea::redraw() if needed.
397 bool const need_second_step =
398 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
399 && (fitCursor() || multiParSel());
401 return need_second_step;
405 void BufferView::updateScrollbar()
408 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
409 << " no text in updateScrollbar" << endl;
410 scrollbarParameters_.reset();
414 LyXText & t = buffer_->text();
415 int const parsize = int(t.paragraphs().size() - 1);
416 if (anchor_ref_ > parsize) {
417 anchor_ref_ = parsize;
422 << BOOST_CURRENT_FUNCTION
423 << " Updating scrollbar: height: " << t.paragraphs().size()
424 << " curr par: " << cursor_.bottom().pit()
425 << " default height " << defaultRowHeight() << endl;
427 // It would be better to fix the scrollbar to understand
428 // values in [0..1] and divide everything by wh
430 // estimated average paragraph height:
433 int h = t.getPar(anchor_ref_).height();
435 // Normalize anchor/offset (MV):
436 while (offset_ref_ > h && anchor_ref_ < parsize) {
439 h = t.getPar(anchor_ref_).height();
441 // Look at paragraph heights on-screen
444 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
447 int const h2 = t.getPar(pit).height();
451 int const hav = sumh / nh;
452 // More realistic average paragraph height
456 scrollbarParameters_.height = (parsize + 1) * wh_;
457 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
458 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
462 ScrollbarParameters const & BufferView::scrollbarParameters() const
464 return scrollbarParameters_;
468 void BufferView::scrollDocView(int value)
470 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
471 << "[ value = " << value << "]" << endl;
476 LyXText & t = buffer_->text();
478 float const bar = value / float(wh_ * t.paragraphs().size());
480 anchor_ref_ = int(bar * t.paragraphs().size());
481 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
482 anchor_ref_ = int(t.paragraphs().size()) - 1;
483 t.redoParagraph(anchor_ref_);
484 int const h = t.getPar(anchor_ref_).height();
485 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
489 void BufferView::setCursorFromScrollbar()
491 LyXText & t = buffer_->text();
493 int const height = 2 * defaultRowHeight();
494 int const first = height;
495 int const last = height_ - height;
496 LCursor & cur = cursor_;
498 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
501 case bv_funcs::CUR_ABOVE:
502 t.setCursorFromCoordinates(cur, 0, first);
503 cur.clearSelection();
505 case bv_funcs::CUR_BELOW:
506 t.setCursorFromCoordinates(cur, 0, last);
507 cur.clearSelection();
509 case bv_funcs::CUR_INSIDE:
510 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
511 int const newy = min(last, max(y, first));
513 cur.reset(buffer_->inset());
514 t.setCursorFromCoordinates(cur, 0, newy);
520 Change const BufferView::getCurrentChange()
522 if (!buffer_->params().tracking_changes || !cursor_.selection())
523 return Change(Change::UNCHANGED);
525 DocIterator dit = cursor_.selectionBegin();
526 return dit.paragraph().lookupChange(dit.pos());
530 void BufferView::savePosition(unsigned int i)
532 if (i >= saved_positions_num)
534 BOOST_ASSERT(cursor_.inTexted());
535 saved_positions[i] = Position(buffer_->fileName(),
536 cursor_.paragraph().id(),
539 // emit message signal.
540 message(bformat(_("Saved bookmark %1$d"), i));
544 void BufferView::restorePosition(unsigned int i)
546 if (i >= saved_positions_num)
549 string const fname = saved_positions[i].filename;
551 cursor_.clearSelection();
553 if (fname != buffer_->fileName()) {
555 if (bufferlist.exists(fname))
556 b = bufferlist.getBuffer(fname);
558 b = bufferlist.newBuffer(fname);
559 // Don't ask, just load it
560 ::loadLyXFile(b, fname);
566 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
567 if (par == buffer_->par_iterator_end())
570 setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
573 // emit message signal.
574 message(bformat(_("Moved to bookmark %1$d"), i));
578 bool BufferView::isSavedPosition(unsigned int i)
580 return i < saved_positions_num && !saved_positions[i].filename.empty();
583 void BufferView::saveSavedPositions()
585 // save bookmarks. It is better to use the pit interface
586 // but I do not know how to effectively convert between
588 for (unsigned int i=1; i < saved_positions_num; ++i) {
589 if ( isSavedPosition(i) )
590 LyX::ref().session().saveBookmark( boost::tie(
592 saved_positions[i].filename,
593 saved_positions[i].par_id,
594 saved_positions[i].par_pos) );
598 void BufferView::switchKeyMap()
600 if (!lyxrc.rtl_support)
603 Intl & intl = owner_->getIntl();
604 if (getLyXText()->real_current_font.isRightToLeft()) {
605 if (intl.keymap == Intl::PRIMARY)
608 if (intl.keymap == Intl::SECONDARY)
614 int BufferView::workWidth() const
620 void BufferView::center()
622 CursorSlice & bot = cursor_.bottom();
623 lyx::pit_type const pit = bot.pit();
624 bot.text()->redoParagraph(pit);
625 Paragraph const & par = bot.text()->paragraphs()[pit];
627 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
628 + par.ascent() - height_ / 2;
632 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
636 switch (cmd.action) {
639 flag.enabled(!buffer_->undostack().empty());
642 flag.enabled(!buffer_->redostack().empty());
644 case LFUN_FILE_INSERT:
645 case LFUN_FILE_INSERT_ASCII_PARA:
646 case LFUN_FILE_INSERT_ASCII:
647 case LFUN_BOOKMARK_SAVE:
648 // FIXME: Actually, these LFUNS should be moved to LyXText
649 flag.enabled(cursor_.inTexted());
651 case LFUN_FONT_STATE:
652 case LFUN_LABEL_INSERT:
653 case LFUN_PARAGRAPH_GOTO:
654 // FIXME handle non-trivially
655 case LFUN_OUTLINE_UP:
656 case LFUN_OUTLINE_DOWN:
657 case LFUN_OUTLINE_IN:
658 case LFUN_OUTLINE_OUT:
660 case LFUN_REFERENCE_NEXT:
662 case LFUN_WORD_REPLACE:
665 case LFUN_MARK_TOGGLE:
666 case LFUN_SCREEN_RECENTER:
667 case LFUN_BIBTEX_DATABASE_ADD:
668 case LFUN_BIBTEX_DATABASE_DEL:
669 case LFUN_WORDS_COUNT:
670 case LFUN_NEXT_INSET_TOGGLE:
674 case LFUN_LABEL_GOTO: {
675 flag.enabled(!cmd.argument().empty()
676 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
680 case LFUN_BOOKMARK_GOTO:
681 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
683 case LFUN_CHANGES_TRACK:
685 flag.setOnOff(buffer_->params().tracking_changes);
688 case LFUN_CHANGES_OUTPUT: {
689 OutputParams runparams;
690 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
691 flag.enabled(buffer_ && buffer_->params().tracking_changes
692 && features.isAvailable("dvipost"));
693 flag.setOnOff(buffer_->params().output_changes);
697 case LFUN_CHANGES_MERGE:
698 case LFUN_CHANGE_ACCEPT: // what about these two
699 case LFUN_CHANGE_REJECT: // what about these two
700 case LFUN_ALL_CHANGES_ACCEPT:
701 case LFUN_ALL_CHANGES_REJECT:
702 flag.enabled(buffer_ && buffer_->params().tracking_changes);
705 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
706 flag.setOnOff(buffer_->params().compressed);
718 bool BufferView::dispatch(FuncRequest const & cmd)
720 //lyxerr << BOOST_CURRENT_FUNCTION
721 // << [ cmd = " << cmd << "]" << endl;
723 // Make sure that the cached BufferView is correct.
724 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
725 << " action[" << cmd.action << ']'
726 << " arg[" << lyx::to_utf8(cmd.argument()) << ']'
727 << " x[" << cmd.x << ']'
728 << " y[" << cmd.y << ']'
729 << " button[" << cmd.button() << ']'
732 LCursor & cur = cursor_;
734 switch (cmd.action) {
738 cur.message(_("Undo"));
739 cur.clearSelection();
740 if (!textUndo(*this))
741 cur.message(_("No further undo information"));
749 cur.message(_("Redo"));
750 cur.clearSelection();
751 if (!textRedo(*this))
752 cur.message(_("No further redo information"));
758 case LFUN_FILE_INSERT:
759 // FIXME: We don't know the encoding of filenames
760 menuInsertLyXFile(lyx::to_utf8(cmd.argument()));
763 case LFUN_FILE_INSERT_ASCII_PARA:
764 // FIXME: We don't know the encoding of filenames
765 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), true);
768 case LFUN_FILE_INSERT_ASCII:
769 // FIXME: We don't know the encoding of filenames
770 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), false);
773 case LFUN_FONT_STATE:
774 cur.message(lyx::from_utf8(cur.currentState()));
777 case LFUN_BOOKMARK_SAVE:
778 savePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
781 case LFUN_BOOKMARK_GOTO:
782 restorePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
785 case LFUN_LABEL_GOTO: {
786 string label = lyx::to_utf8(cmd.argument());
789 getInsetByCode<InsetRef>(cursor_,
790 InsetBase::REF_CODE);
792 label = inset->getContents();
802 case LFUN_PARAGRAPH_GOTO: {
803 int const id = convert<int>(lyx::to_utf8(cmd.argument()));
804 ParIterator par = buffer_->getParFromID(id);
805 if (par == buffer_->par_iterator_end()) {
806 lyxerr[Debug::INFO] << "No matching paragraph found! ["
807 << id << ']' << endl;
810 lyxerr[Debug::INFO] << "Paragraph " << par->id()
811 << " found." << endl;
815 setCursor(makeDocIterator(par, 0));
822 case LFUN_OUTLINE_UP:
823 lyx::toc::outline(lyx::toc::Up, cursor_);
824 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
825 updateLabels(*buffer_);
827 case LFUN_OUTLINE_DOWN:
828 lyx::toc::outline(lyx::toc::Down, cursor_);
829 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
830 updateLabels(*buffer_);
832 case LFUN_OUTLINE_IN:
833 lyx::toc::outline(lyx::toc::In, cursor_);
834 updateLabels(*buffer_);
836 case LFUN_OUTLINE_OUT:
837 lyx::toc::outline(lyx::toc::Out, cursor_);
838 updateLabels(*buffer_);
842 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
845 case LFUN_REFERENCE_NEXT: {
846 vector<InsetBase_code> tmp;
847 tmp.push_back(InsetBase::LABEL_CODE);
848 tmp.push_back(InsetBase::REF_CODE);
849 bv_funcs::gotoInset(this, tmp, true);
853 case LFUN_CHANGES_TRACK:
857 case LFUN_CHANGES_OUTPUT: {
858 bool const state = buffer_->params().output_changes;
859 buffer_->params().output_changes = !state;
863 case LFUN_CHANGES_MERGE:
864 if (lyx::find::findNextChange(this))
865 owner_->getDialogs().show("changes");
868 case LFUN_ALL_CHANGES_ACCEPT: {
869 cursor_.reset(buffer_->inset());
871 #warning FIXME changes
873 while (lyx::find::findNextChange(this))
874 getLyXText()->acceptChange(cursor_);
879 case LFUN_ALL_CHANGES_REJECT: {
880 cursor_.reset(buffer_->inset());
882 #warning FIXME changes
884 while (lyx::find::findNextChange(this))
885 getLyXText()->rejectChange(cursor_);
890 lyx::find::find(this, cmd);
893 case LFUN_WORD_REPLACE:
894 lyx::find::replace(this, cmd);
898 cur.clearSelection();
900 cur.message(lyx::from_utf8(N_("Mark off")));
904 cur.clearSelection();
907 cur.message(lyx::from_utf8(N_("Mark on")));
910 case LFUN_MARK_TOGGLE:
911 cur.clearSelection();
914 cur.message(lyx::from_utf8(N_("Mark removed")));
917 cur.message(lyx::from_utf8(N_("Mark set")));
922 case LFUN_SCREEN_RECENTER:
926 case LFUN_BIBTEX_DATABASE_ADD: {
927 LCursor tmpcur = cursor_;
928 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
929 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
930 InsetBase::BIBTEX_CODE);
932 if (inset->addDatabase(lyx::to_utf8(cmd.argument())))
933 buffer_->updateBibfilesCache();
938 case LFUN_BIBTEX_DATABASE_DEL: {
939 LCursor tmpcur = cursor_;
940 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
941 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
942 InsetBase::BIBTEX_CODE);
944 if (inset->delDatabase(lyx::to_utf8(cmd.argument())))
945 buffer_->updateBibfilesCache();
950 case LFUN_WORDS_COUNT: {
951 DocIterator from, to;
952 if (cur.selection()) {
953 from = cur.selectionBegin();
954 to = cur.selectionEnd();
956 from = doc_iterator_begin(buffer_->inset());
957 to = doc_iterator_end(buffer_->inset());
959 int const count = countWords(from, to);
963 message = bformat(_("%1$d words in selection."),
966 message = bformat(_("%1$d words in document."),
971 message = _("One word in selection.");
973 message = _("One word in document.");
976 Alert::information(_("Count words"), message);
980 case LFUN_BUFFER_TOGGLE_COMPRESSION:
981 // turn compression on/off
982 buffer_->params().compressed = !buffer_->params().compressed;
985 case LFUN_NEXT_INSET_TOGGLE: {
986 // this is the real function we want to invoke
987 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
988 // if there is an inset at cursor, see whether it
990 InsetBase * inset = cur.nextInset();
991 if (inset && inset->isActive()) {
992 LCursor tmpcur = cur;
993 tmpcur.pushLeft(*inset);
994 inset->dispatch(tmpcur, tmpcmd);
995 if (tmpcur.result().dispatched()) {
999 // if it did not work, try the underlying inset.
1000 if (!cur.result().dispatched())
1001 cur.dispatch(tmpcmd);
1003 if (cur.result().dispatched())
1004 cur.clearSelection();
1017 docstring const BufferView::requestSelection()
1022 LCursor & cur = cursor_;
1024 if (!cur.selection()) {
1025 xsel_cache_.set = false;
1029 if (!xsel_cache_.set ||
1030 cur.top() != xsel_cache_.cursor ||
1031 cur.anchor_.top() != xsel_cache_.anchor)
1033 xsel_cache_.cursor = cur.top();
1034 xsel_cache_.anchor = cur.anchor_.top();
1035 xsel_cache_.set = cur.selection();
1036 return cur.selectionAsString(false);
1042 void BufferView::clearSelection()
1045 cursor_.clearSelection();
1046 xsel_cache_.set = false;
1051 void BufferView::workAreaResize(int width, int height)
1053 bool const widthChange = width != width_;
1054 bool const heightChange = height != height_;
1056 // Update from work area
1060 if (buffer_ && widthChange) {
1061 // The WorkArea content needs a resize
1065 if (widthChange || heightChange)
1070 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1072 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1074 // This is only called for mouse related events including
1075 // LFUN_FILE_OPEN generated by drag-and-drop.
1076 FuncRequest cmd = cmd0;
1082 cur.push(buffer_->inset());
1083 cur.selection() = cursor_.selection();
1085 // Doesn't go through lyxfunc, so we need to update
1086 // the layout choice etc. ourselves
1088 // E.g. Qt mouse press when no buffer
1092 // Either the inset under the cursor or the
1093 // surrounding LyXText will handle this event.
1095 // Build temporary cursor.
1096 cmd.y = min(max(cmd.y, -1), height_);
1097 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1098 //lyxerr << BOOST_CURRENT_FUNCTION
1099 // << " * hit inset at tip: " << inset << endl;
1100 //lyxerr << BOOST_CURRENT_FUNCTION
1101 // << " * created temp cursor:" << cur << endl;
1103 // Put anchor at the same position.
1106 // Try to dispatch to an non-editable inset near this position
1107 // via the temp cursor. If the inset wishes to change the real
1108 // cursor it has to do so explicitly by using
1109 // cur.bv().cursor() = cur; (or similar)
1111 inset->dispatch(cur, cmd);
1113 // Now dispatch to the temporary cursor. If the real cursor should
1114 // be modified, the inset's dispatch has to do so explicitly.
1115 if (!cur.result().dispatched())
1118 if (cur.result().dispatched()) {
1119 // Redraw if requested or necessary.
1120 if (cur.result().update())
1121 update(Update::FitCursor | Update::Force);
1123 update(Update::FitCursor | Update::MultiParSel);
1130 void BufferView::scroll(int lines)
1135 // LyXText const * t = &buffer_->text();
1136 // int const line_height = defaultRowHeight();
1138 // // The new absolute coordinate
1139 // int new_top_y = top_y() + lines * line_height;
1141 // // Restrict to a valid value
1142 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1143 // new_top_y = std::max(0, new_top_y);
1145 // scrollDocView(new_top_y);
1147 // // Update the scrollbar.
1148 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1152 void BufferView::setCursorFromRow(int row)
1157 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1160 buffer_->text().setCursor(cursor_, 0, 0);
1162 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1166 void BufferView::gotoLabel(string const & label)
1168 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1169 vector<string> labels;
1170 it->getLabelList(*buffer_, labels);
1171 if (find(labels.begin(),labels.end(),label) != labels.end()) {
1180 LyXText * BufferView::getLyXText()
1182 LyXText * text = cursor_.innerText();
1188 LyXText const * BufferView::getLyXText() const
1190 LyXText const * text = cursor_.innerText();
1196 int BufferView::workHeight() const
1202 void BufferView::setCursor(DocIterator const & dit)
1204 size_t const n = dit.depth();
1205 for (size_t i = 0; i < n; ++i)
1206 dit[i].inset().edit(cursor_, true);
1208 cursor_.setCursor(dit);
1209 cursor_.selection() = false;
1213 void BufferView::mouseSetCursor(LCursor & cur)
1215 BOOST_ASSERT(&cur.bv() == this);
1217 // Has the cursor just left the inset?
1218 bool badcursor = false;
1219 if (&cursor_.inset() != &cur.inset())
1220 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1222 // do the dEPM magic if needed
1223 // FIXME: move this to InsetText::notifyCursorLeaves?
1224 if (!badcursor && cursor_.inTexted())
1225 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1228 cursor_.clearSelection();
1229 cursor_.setTargetX();
1235 void BufferView::putSelectionAt(DocIterator const & cur,
1236 int length, bool backwards)
1238 cursor_.clearSelection();
1244 cursor_.pos() += length;
1245 cursor_.setSelection(cursor_, -length);
1247 cursor_.setSelection(cursor_, length);
1252 LCursor & BufferView::cursor()
1258 LCursor const & BufferView::cursor() const
1264 lyx::pit_type BufferView::anchor_ref() const
1270 int BufferView::offset_ref() const
1276 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1278 return metrics_info_;
1282 void BufferView::updateMetrics(bool singlepar)
1284 // Remove old position cache
1286 LyXText & buftext = buffer_->text();
1287 lyx::pit_type size = int(buftext.paragraphs().size());
1289 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1290 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1294 lyx::pit_type const pit = anchor_ref_;
1297 size_t const npit = buftext.paragraphs().size();
1299 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1300 // the (main text, not inset!) paragraph containing the cursor.
1301 // (if this paragraph contains insets etc., rebreaking will
1302 // recursively descend)
1303 if (!singlepar || pit == cursor_.bottom().pit())
1304 buftext.redoParagraph(pit);
1305 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1307 // Redo paragraphs above anchor if necessary; again, in Single Par
1308 // mode, only if we encounter the (main text) one having the cursor.
1310 while (y1 > 0 && pit1 > 0) {
1311 y1 -= buftext.getPar(pit1).ascent();
1313 if (!singlepar || pit1 == cursor_.bottom().pit())
1314 buftext.redoParagraph(pit1);
1315 y1 -= buftext.getPar(pit1).descent();
1319 // Take care of ascent of first line
1320 y1 -= buftext.getPar(pit1).ascent();
1322 // Normalize anchor for next time
1326 // Grey at the beginning is ugly
1327 if (pit1 == 0 && y1 > 0) {
1333 // Redo paragraphs below the anchor if necessary. Single par mode:
1334 // only the one containing the cursor if encountered.
1336 while (y2 < height_ && pit2 < int(npit) - 1) {
1337 y2 += buftext.getPar(pit2).descent();
1339 if (!singlepar || pit2 == cursor_.bottom().pit())
1340 buftext.redoParagraph(pit2);
1341 y2 += buftext.getPar(pit2).ascent();
1344 // Take care of descent of last line
1345 y2 += buftext.getPar(pit2).descent();
1347 // The coordinates of all these paragraphs are correct, cache them
1349 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[&buftext];
1350 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1351 Paragraph const & par = buftext.getPar(pit);
1353 parPos[pit] = Point(0, y);
1354 if (singlepar && pit == cursor_.bottom().pit()) {
1355 // In Single Paragraph mode, collect here the
1356 // y1 and y2 of the (one) paragraph the cursor is in
1357 y1 = y - par.ascent();
1358 y2 = y + par.descent();
1364 // collect cursor paragraph iter bounds
1365 pit1 = cursor_.bottom().pit();
1366 pit2 = cursor_.bottom().pit();
1369 lyxerr[Debug::DEBUG]
1370 << BOOST_CURRENT_FUNCTION
1373 << " pit1: " << pit1
1374 << " pit2: " << pit2
1375 << " npit: " << npit
1376 << " singlepar: " << singlepar
1380 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1384 void BufferView::menuInsertLyXFile(string const & filenm)
1386 BOOST_ASSERT(cursor_.inTexted());
1387 string filename = filenm;
1389 if (filename.empty()) {
1390 // Launch a file browser
1391 string initpath = lyxrc.document_path;
1394 string const trypath = buffer_->filePath();
1395 // If directory is writeable, use this as default.
1396 if (isDirWriteable(trypath))
1400 FileDialog fileDlg(lyx::to_utf8(_("Select LyX document to insert")),
1402 make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
1403 string(lyxrc.document_path)),
1404 make_pair(string(lyx::to_utf8(_("Examples|#E#e"))),
1405 string(addPath(package().system_support(), "examples"))));
1407 FileDialog::Result result =
1408 fileDlg.open(initpath,
1409 FileFilterList(lyx::to_utf8(_("LyX Documents (*.lyx)"))),
1412 if (result.first == FileDialog::Later)
1415 filename = result.second;
1417 // check selected filename
1418 if (filename.empty()) {
1419 // emit message signal.
1420 message(_("Canceled."));
1425 // Get absolute path of file and add ".lyx"
1426 // to the filename if necessary
1427 filename = fileSearch(string(), filename, "lyx");
1429 docstring const disp_fn = makeDisplayPath(filename);
1430 // emit message signal.
1431 message(bformat(_("Inserting document %1$s..."), disp_fn));
1434 Buffer buf("", false);
1435 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
1436 ErrorList & el = buffer_->errorList("Parse");
1437 // Copy the inserted document error list into the current buffer one.
1438 el = buf.errorList("Parse");
1439 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
1440 buf.params().textclass, el);
1441 res = _("Document %1$s inserted.");
1443 res = _("Could not insert document %1$s");
1445 // emit message signal.
1446 message(bformat(res, disp_fn));
1447 buffer_->errors("Parse");
1452 void BufferView::trackChanges()
1454 bool const tracking = buffer_->params().tracking_changes;
1457 for_each(buffer_->par_iterator_begin(),
1458 buffer_->par_iterator_end(),
1459 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
1460 buffer_->params().tracking_changes = true;
1462 // We cannot allow undos beyond the freeze point
1463 buffer_->undostack().clear();
1465 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
1466 if (lyx::find::findNextChange(this)) {
1467 owner_->getDialogs().show("changes");
1471 for_each(buffer_->par_iterator_begin(),
1472 buffer_->par_iterator_end(),
1473 mem_fun_ref(&Paragraph::untrackChanges));
1475 buffer_->params().tracking_changes = false;
1478 buffer_->redostack().clear();