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/Application.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/font_metrics.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>
85 using lyx::support::addPath;
86 using lyx::support::bformat;
87 using lyx::support::FileFilterList;
88 using lyx::support::fileSearch;
89 using lyx::support::isDirWriteable;
90 using lyx::support::makeDisplayPath;
91 using lyx::support::makeAbsPath;
92 using lyx::support::package;
96 using std::istringstream;
101 using std::mem_fun_ref;
108 unsigned int const saved_positions_num = 20;
111 /// Return an inset of this class if it exists at the current cursor position
113 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
116 DocIterator it = cur;
117 if (it.nextInset() &&
118 it.nextInset()->lyxCode() == code) {
119 inset = static_cast<T*>(it.nextInset());
127 BufferView::BufferView()
128 : buffer_(0), wh_(0),
130 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
133 xsel_cache_.set = false;
135 saved_positions.resize(saved_positions_num);
136 // load saved bookmarks
137 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
138 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
139 bm != bmList.end(); ++bm)
140 if (bm->get<0>() < saved_positions_num)
141 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
142 // and then clear them
145 intl_->initKeyMapper(lyxrc.use_kbmap);
149 BufferView::~BufferView()
154 Buffer * BufferView::buffer() const
160 void BufferView::setBuffer(Buffer * b)
162 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
163 << "[ b = " << b << "]" << endl;
166 // Save the actual cursor position and anchor inside the
167 // buffer so that it can be restored in case we rechange
168 // to this buffer later on.
169 buffer_->saveCursor(cursor_.selectionBegin(),
170 cursor_.selectionEnd());
171 // current buffer is going to be switched-off, save cursor pos
172 LyX::ref().session().saveFilePosition(buffer_->fileName(),
173 boost::tie(cursor_.pit(), cursor_.pos()) );
176 // If we're quitting lyx, don't bother updating stuff
182 // If we are closing current buffer, switch to the first in
185 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
186 << " No Buffer!" << endl;
187 // We are closing the buffer, use the first buffer as current
188 buffer_ = theApp->bufferList().first();
190 // Set current buffer
195 cursor_ = LCursor(*this);
200 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
201 << "Buffer addr: " << buffer_ << endl;
202 cursor_.push(buffer_->inset());
203 cursor_.resetAnchor();
204 buffer_->text().init(this);
205 buffer_->text().setCurrentFont(cursor_);
206 if (buffer_->getCursor().size() > 0 &&
207 buffer_->getAnchor().size() > 0)
209 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
210 cursor_.resetAnchor();
211 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
212 cursor_.setSelection();
218 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
219 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
223 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
225 // Get absolute path of file and add ".lyx"
226 // to the filename if necessary
227 string s = fileSearch(string(), filename, "lyx");
229 bool const found = !s.empty();
234 // File already open?
235 if (theApp->bufferList().exists(s)) {
236 docstring const file = makeDisplayPath(s, 20);
237 docstring text = bformat(_("The document %1$s is already "
238 "loaded.\n\nDo you want to revert "
239 "to the saved version?"), file);
240 int const ret = Alert::prompt(_("Revert to saved document?"),
241 text, 0, 1, _("&Revert"), _("&Switch to document"));
244 setBuffer(theApp->bufferList().getBuffer(s));
247 // FIXME: should be LFUN_REVERT
248 if (!theApp->bufferList().close(theApp->bufferList().getBuffer(s), false))
250 // Fall through to new load. (Asger)
256 b = theApp->bufferList().newBuffer(s);
257 if (!::loadLyXFile(b, s)) {
258 theApp->bufferList().release(b);
262 docstring text = bformat(_("The document %1$s does not yet "
263 "exist.\n\nDo you want to create "
264 "a new document?"), lyx::from_utf8(s));
265 int const ret = Alert::prompt(_("Create new document?"),
266 text, 0, 1, _("&Create"), _("Cancel"));
269 b = newFile(s, string(), true);
277 // Send the "errors" signal in case of parsing errors
280 // scroll to the position when the file was last closed
281 if (lyxrc.use_lastfilepos) {
284 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
285 // I am not sure how to separate the following part to a function
286 // so I will leave this to Lars.
288 // check pit since the document may be externally changed.
289 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
290 ParIterator it = b->par_iterator_begin();
291 ParIterator const end = b->par_iterator_end();
292 for (; it != end; ++it)
293 if (it.pit() == pit) {
294 // restored pos may be bigger than it->size
295 setCursor(makeDocIterator(it, min(pos, it->size())));
296 update(Update::FitCursor);
303 LyX::ref().session().addLastFile(b->fileName());
309 void BufferView::reload()
311 string const fn = buffer_->fileName();
312 if (theApp->bufferList().close(buffer_, false))
317 void BufferView::resize()
322 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
324 buffer_->text().init(this);
330 bool BufferView::fitCursor()
332 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
333 LyXFont const font = cursor_.getFont();
334 int const asc = font_metrics::maxAscent(font);
335 int const des = font_metrics::maxDescent(font);
336 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
337 if (p.y_ - asc >= 0 && p.y_ + des < height_)
345 bool BufferView::multiParSel()
347 if (!cursor_.selection())
349 bool ret = multiparsel_cache_;
350 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
351 // Either this, or previous selection spans paragraphs
352 return ret || multiparsel_cache_;
356 bool BufferView::update(Update::flags flags)
358 // This is close to a hot-path.
359 if (lyxerr.debugging(Debug::DEBUG)) {
361 << BOOST_CURRENT_FUNCTION
362 << "[fitcursor = " << (flags & Update::FitCursor)
363 << ", forceupdate = " << (flags & Update::Force)
364 << ", singlepar = " << (flags & Update::SinglePar)
365 << "] buffer: " << buffer_ << endl;
368 // Check needed to survive LyX startup
372 // Update macro store
373 buffer_->buildMacros();
375 // First drawing step
376 updateMetrics(flags & Update::SinglePar);
378 // The second drawing step is done in WorkArea::redraw() if needed.
379 bool const need_second_step =
380 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
381 && (fitCursor() || multiParSel());
383 return need_second_step;
387 void BufferView::updateScrollbar()
390 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
391 << " no text in updateScrollbar" << endl;
392 scrollbarParameters_.reset();
396 LyXText & t = buffer_->text();
397 int const parsize = int(t.paragraphs().size() - 1);
398 if (anchor_ref_ > parsize) {
399 anchor_ref_ = parsize;
404 << BOOST_CURRENT_FUNCTION
405 << " Updating scrollbar: height: " << t.paragraphs().size()
406 << " curr par: " << cursor_.bottom().pit()
407 << " default height " << defaultRowHeight() << endl;
409 // It would be better to fix the scrollbar to understand
410 // values in [0..1] and divide everything by wh
412 // estimated average paragraph height:
415 int h = t.getPar(anchor_ref_).height();
417 // Normalize anchor/offset (MV):
418 while (offset_ref_ > h && anchor_ref_ < parsize) {
421 h = t.getPar(anchor_ref_).height();
423 // Look at paragraph heights on-screen
426 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
429 int const h2 = t.getPar(pit).height();
433 int const hav = sumh / nh;
434 // More realistic average paragraph height
438 scrollbarParameters_.height = (parsize + 1) * wh_;
439 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
440 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
444 ScrollbarParameters const & BufferView::scrollbarParameters() const
446 return scrollbarParameters_;
450 void BufferView::scrollDocView(int value)
452 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
453 << "[ value = " << value << "]" << endl;
458 LyXText & t = buffer_->text();
460 float const bar = value / float(wh_ * t.paragraphs().size());
462 anchor_ref_ = int(bar * t.paragraphs().size());
463 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
464 anchor_ref_ = int(t.paragraphs().size()) - 1;
465 t.redoParagraph(anchor_ref_);
466 int const h = t.getPar(anchor_ref_).height();
467 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
471 void BufferView::setCursorFromScrollbar()
473 LyXText & t = buffer_->text();
475 int const height = 2 * defaultRowHeight();
476 int const first = height;
477 int const last = height_ - height;
478 LCursor & cur = cursor_;
480 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
483 case bv_funcs::CUR_ABOVE:
484 t.setCursorFromCoordinates(cur, 0, first);
485 cur.clearSelection();
487 case bv_funcs::CUR_BELOW:
488 t.setCursorFromCoordinates(cur, 0, last);
489 cur.clearSelection();
491 case bv_funcs::CUR_INSIDE:
492 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
493 int const newy = min(last, max(y, first));
495 cur.reset(buffer_->inset());
496 t.setCursorFromCoordinates(cur, 0, newy);
502 Change const BufferView::getCurrentChange()
504 if (!buffer_->params().tracking_changes || !cursor_.selection())
505 return Change(Change::UNCHANGED);
507 DocIterator dit = cursor_.selectionBegin();
508 return dit.paragraph().lookupChange(dit.pos());
512 void BufferView::savePosition(unsigned int i)
514 if (i >= saved_positions_num)
516 BOOST_ASSERT(cursor_.inTexted());
517 saved_positions[i] = Position(buffer_->fileName(),
518 cursor_.paragraph().id(),
521 // emit message signal.
522 message(bformat(_("Saved bookmark %1$d"), i));
526 void BufferView::restorePosition(unsigned int i)
528 if (i >= saved_positions_num)
531 string const fname = saved_positions[i].filename;
533 cursor_.clearSelection();
535 if (fname != buffer_->fileName()) {
537 if (theApp->bufferList().exists(fname))
538 b = theApp->bufferList().getBuffer(fname);
540 b = theApp->bufferList().newBuffer(fname);
541 // Don't ask, just load it
542 ::loadLyXFile(b, fname);
548 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
549 if (par == buffer_->par_iterator_end())
552 setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
555 // emit message signal.
556 message(bformat(_("Moved to bookmark %1$d"), i));
560 bool BufferView::isSavedPosition(unsigned int i)
562 return i < saved_positions_num && !saved_positions[i].filename.empty();
565 void BufferView::saveSavedPositions()
567 // save bookmarks. It is better to use the pit interface
568 // but I do not know how to effectively convert between
570 for (unsigned int i=1; i < saved_positions_num; ++i) {
571 if ( isSavedPosition(i) )
572 LyX::ref().session().saveBookmark( boost::tie(
574 saved_positions[i].filename,
575 saved_positions[i].par_id,
576 saved_positions[i].par_pos) );
580 void BufferView::switchKeyMap()
582 if (!lyxrc.rtl_support)
585 if (getLyXText()->real_current_font.isRightToLeft()) {
586 if (intl_->keymap == Intl::PRIMARY)
589 if (intl_->keymap == Intl::SECONDARY)
595 int BufferView::workWidth() const
601 void BufferView::center()
603 CursorSlice & bot = cursor_.bottom();
604 lyx::pit_type const pit = bot.pit();
605 bot.text()->redoParagraph(pit);
606 Paragraph const & par = bot.text()->paragraphs()[pit];
608 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
609 + par.ascent() - height_ / 2;
613 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
617 switch (cmd.action) {
620 flag.enabled(!buffer_->undostack().empty());
623 flag.enabled(!buffer_->redostack().empty());
625 case LFUN_FILE_INSERT:
626 case LFUN_FILE_INSERT_ASCII_PARA:
627 case LFUN_FILE_INSERT_ASCII:
628 case LFUN_BOOKMARK_SAVE:
629 // FIXME: Actually, these LFUNS should be moved to LyXText
630 flag.enabled(cursor_.inTexted());
632 case LFUN_FONT_STATE:
633 case LFUN_LABEL_INSERT:
634 case LFUN_PARAGRAPH_GOTO:
635 // FIXME handle non-trivially
636 case LFUN_OUTLINE_UP:
637 case LFUN_OUTLINE_DOWN:
638 case LFUN_OUTLINE_IN:
639 case LFUN_OUTLINE_OUT:
641 case LFUN_REFERENCE_NEXT:
643 case LFUN_WORD_REPLACE:
646 case LFUN_MARK_TOGGLE:
647 case LFUN_SCREEN_RECENTER:
648 case LFUN_BIBTEX_DATABASE_ADD:
649 case LFUN_BIBTEX_DATABASE_DEL:
650 case LFUN_WORDS_COUNT:
651 case LFUN_NEXT_INSET_TOGGLE:
655 case LFUN_LABEL_GOTO: {
656 flag.enabled(!cmd.argument().empty()
657 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
661 case LFUN_BOOKMARK_GOTO:
662 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
664 case LFUN_CHANGES_TRACK:
666 flag.setOnOff(buffer_->params().tracking_changes);
669 case LFUN_CHANGES_OUTPUT: {
670 OutputParams runparams;
671 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
672 flag.enabled(buffer_ && buffer_->params().tracking_changes
673 && features.isAvailable("dvipost"));
674 flag.setOnOff(buffer_->params().output_changes);
678 case LFUN_CHANGES_MERGE:
679 case LFUN_CHANGE_ACCEPT: // what about these two
680 case LFUN_CHANGE_REJECT: // what about these two
681 case LFUN_ALL_CHANGES_ACCEPT:
682 case LFUN_ALL_CHANGES_REJECT:
683 flag.enabled(buffer_ && buffer_->params().tracking_changes);
686 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
687 flag.setOnOff(buffer_->params().compressed);
699 bool BufferView::dispatch(FuncRequest const & cmd)
701 //lyxerr << BOOST_CURRENT_FUNCTION
702 // << [ cmd = " << cmd << "]" << endl;
704 // Make sure that the cached BufferView is correct.
705 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
706 << " action[" << cmd.action << ']'
707 << " arg[" << lyx::to_utf8(cmd.argument()) << ']'
708 << " x[" << cmd.x << ']'
709 << " y[" << cmd.y << ']'
710 << " button[" << cmd.button() << ']'
713 LCursor & cur = cursor_;
715 switch (cmd.action) {
719 cur.message(_("Undo"));
720 cur.clearSelection();
721 if (!textUndo(*this))
722 cur.message(_("No further undo information"));
730 cur.message(_("Redo"));
731 cur.clearSelection();
732 if (!textRedo(*this))
733 cur.message(_("No further redo information"));
739 case LFUN_FILE_INSERT:
740 // FIXME: We don't know the encoding of filenames
741 menuInsertLyXFile(lyx::to_utf8(cmd.argument()));
744 case LFUN_FILE_INSERT_ASCII_PARA:
745 // FIXME: We don't know the encoding of filenames
746 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), true);
749 case LFUN_FILE_INSERT_ASCII:
750 // FIXME: We don't know the encoding of filenames
751 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), false);
754 case LFUN_FONT_STATE:
755 cur.message(lyx::from_utf8(cur.currentState()));
758 case LFUN_BOOKMARK_SAVE:
759 savePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
762 case LFUN_BOOKMARK_GOTO:
763 restorePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
766 case LFUN_LABEL_GOTO: {
767 string label = lyx::to_utf8(cmd.argument());
770 getInsetByCode<InsetRef>(cursor_,
771 InsetBase::REF_CODE);
773 label = inset->getContents();
783 case LFUN_PARAGRAPH_GOTO: {
784 int const id = convert<int>(lyx::to_utf8(cmd.argument()));
785 ParIterator par = buffer_->getParFromID(id);
786 if (par == buffer_->par_iterator_end()) {
787 lyxerr[Debug::INFO] << "No matching paragraph found! ["
788 << id << ']' << endl;
791 lyxerr[Debug::INFO] << "Paragraph " << par->id()
792 << " found." << endl;
796 setCursor(makeDocIterator(par, 0));
803 case LFUN_OUTLINE_UP:
804 lyx::toc::outline(lyx::toc::Up, cursor_);
805 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
806 updateLabels(*buffer_);
808 case LFUN_OUTLINE_DOWN:
809 lyx::toc::outline(lyx::toc::Down, cursor_);
810 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
811 updateLabels(*buffer_);
813 case LFUN_OUTLINE_IN:
814 lyx::toc::outline(lyx::toc::In, cursor_);
815 updateLabels(*buffer_);
817 case LFUN_OUTLINE_OUT:
818 lyx::toc::outline(lyx::toc::Out, cursor_);
819 updateLabels(*buffer_);
823 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
826 case LFUN_REFERENCE_NEXT: {
827 vector<InsetBase_code> tmp;
828 tmp.push_back(InsetBase::LABEL_CODE);
829 tmp.push_back(InsetBase::REF_CODE);
830 bv_funcs::gotoInset(this, tmp, true);
834 case LFUN_CHANGES_TRACK:
838 case LFUN_CHANGES_OUTPUT: {
839 bool const state = buffer_->params().output_changes;
840 buffer_->params().output_changes = !state;
844 case LFUN_CHANGES_MERGE:
845 if (lyx::find::findNextChange(this))
846 showDialog("changes");
849 case LFUN_ALL_CHANGES_ACCEPT: {
850 cursor_.reset(buffer_->inset());
852 #warning FIXME changes
854 while (lyx::find::findNextChange(this))
855 getLyXText()->acceptChange(cursor_);
860 case LFUN_ALL_CHANGES_REJECT: {
861 cursor_.reset(buffer_->inset());
863 #warning FIXME changes
865 while (lyx::find::findNextChange(this))
866 getLyXText()->rejectChange(cursor_);
871 lyx::find::find(this, cmd);
874 case LFUN_WORD_REPLACE:
875 lyx::find::replace(this, cmd);
879 cur.clearSelection();
881 cur.message(lyx::from_utf8(N_("Mark off")));
885 cur.clearSelection();
888 cur.message(lyx::from_utf8(N_("Mark on")));
891 case LFUN_MARK_TOGGLE:
892 cur.clearSelection();
895 cur.message(lyx::from_utf8(N_("Mark removed")));
898 cur.message(lyx::from_utf8(N_("Mark set")));
903 case LFUN_SCREEN_RECENTER:
907 case LFUN_BIBTEX_DATABASE_ADD: {
908 LCursor tmpcur = cursor_;
909 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
910 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
911 InsetBase::BIBTEX_CODE);
913 if (inset->addDatabase(lyx::to_utf8(cmd.argument())))
914 buffer_->updateBibfilesCache();
919 case LFUN_BIBTEX_DATABASE_DEL: {
920 LCursor tmpcur = cursor_;
921 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
922 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
923 InsetBase::BIBTEX_CODE);
925 if (inset->delDatabase(lyx::to_utf8(cmd.argument())))
926 buffer_->updateBibfilesCache();
931 case LFUN_WORDS_COUNT: {
932 DocIterator from, to;
933 if (cur.selection()) {
934 from = cur.selectionBegin();
935 to = cur.selectionEnd();
937 from = doc_iterator_begin(buffer_->inset());
938 to = doc_iterator_end(buffer_->inset());
940 int const count = countWords(from, to);
944 message = bformat(_("%1$d words in selection."),
947 message = bformat(_("%1$d words in document."),
952 message = _("One word in selection.");
954 message = _("One word in document.");
957 Alert::information(_("Count words"), message);
961 case LFUN_BUFFER_TOGGLE_COMPRESSION:
962 // turn compression on/off
963 buffer_->params().compressed = !buffer_->params().compressed;
966 case LFUN_NEXT_INSET_TOGGLE: {
967 // this is the real function we want to invoke
968 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
969 // if there is an inset at cursor, see whether it
971 InsetBase * inset = cur.nextInset();
972 if (inset && inset->isActive()) {
973 LCursor tmpcur = cur;
974 tmpcur.pushLeft(*inset);
975 inset->dispatch(tmpcur, tmpcmd);
976 if (tmpcur.result().dispatched()) {
980 // if it did not work, try the underlying inset.
981 if (!cur.result().dispatched())
982 cur.dispatch(tmpcmd);
984 if (cur.result().dispatched())
985 cur.clearSelection();
998 docstring const BufferView::requestSelection()
1003 LCursor & cur = cursor_;
1005 if (!cur.selection()) {
1006 xsel_cache_.set = false;
1010 if (!xsel_cache_.set ||
1011 cur.top() != xsel_cache_.cursor ||
1012 cur.anchor_.top() != xsel_cache_.anchor)
1014 xsel_cache_.cursor = cur.top();
1015 xsel_cache_.anchor = cur.anchor_.top();
1016 xsel_cache_.set = cur.selection();
1017 return cur.selectionAsString(false);
1023 void BufferView::clearSelection()
1026 cursor_.clearSelection();
1027 xsel_cache_.set = false;
1032 void BufferView::workAreaResize(int width, int height)
1034 bool const widthChange = width != width_;
1035 bool const heightChange = height != height_;
1037 // Update from work area
1041 if (buffer_ && widthChange) {
1042 // The WorkArea content needs a resize
1046 if (widthChange || heightChange)
1051 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1053 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1055 // This is only called for mouse related events including
1056 // LFUN_FILE_OPEN generated by drag-and-drop.
1057 FuncRequest cmd = cmd0;
1063 cur.push(buffer_->inset());
1064 cur.selection() = cursor_.selection();
1066 // Doesn't go through lyxfunc, so we need to update
1067 // the layout choice etc. ourselves
1069 // E.g. Qt mouse press when no buffer
1073 // Either the inset under the cursor or the
1074 // surrounding LyXText will handle this event.
1076 // Build temporary cursor.
1077 cmd.y = min(max(cmd.y, -1), height_);
1078 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1079 //lyxerr << BOOST_CURRENT_FUNCTION
1080 // << " * hit inset at tip: " << inset << endl;
1081 //lyxerr << BOOST_CURRENT_FUNCTION
1082 // << " * created temp cursor:" << cur << endl;
1084 // Put anchor at the same position.
1087 // Try to dispatch to an non-editable inset near this position
1088 // via the temp cursor. If the inset wishes to change the real
1089 // cursor it has to do so explicitly by using
1090 // cur.bv().cursor() = cur; (or similar)
1092 inset->dispatch(cur, cmd);
1094 // Now dispatch to the temporary cursor. If the real cursor should
1095 // be modified, the inset's dispatch has to do so explicitly.
1096 if (!cur.result().dispatched())
1099 if (cur.result().dispatched()) {
1100 // Redraw if requested or necessary.
1101 if (cur.result().update())
1102 update(Update::FitCursor | Update::Force);
1104 update(Update::FitCursor | Update::MultiParSel);
1111 void BufferView::scroll(int lines)
1116 // LyXText const * t = &buffer_->text();
1117 // int const line_height = defaultRowHeight();
1119 // // The new absolute coordinate
1120 // int new_top_y = top_y() + lines * line_height;
1122 // // Restrict to a valid value
1123 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1124 // new_top_y = std::max(0, new_top_y);
1126 // scrollDocView(new_top_y);
1128 // // Update the scrollbar.
1129 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1133 void BufferView::setCursorFromRow(int row)
1138 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1141 buffer_->text().setCursor(cursor_, 0, 0);
1143 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1147 void BufferView::gotoLabel(string const & label)
1149 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1150 vector<string> labels;
1151 it->getLabelList(*buffer_, labels);
1152 if (find(labels.begin(),labels.end(),label) != labels.end()) {
1161 LyXText * BufferView::getLyXText()
1163 LyXText * text = cursor_.innerText();
1169 LyXText const * BufferView::getLyXText() const
1171 LyXText const * text = cursor_.innerText();
1177 int BufferView::workHeight() const
1183 void BufferView::setCursor(DocIterator const & dit)
1185 size_t const n = dit.depth();
1186 for (size_t i = 0; i < n; ++i)
1187 dit[i].inset().edit(cursor_, true);
1189 cursor_.setCursor(dit);
1190 cursor_.selection() = false;
1194 void BufferView::mouseSetCursor(LCursor & cur)
1196 BOOST_ASSERT(&cur.bv() == this);
1198 // Has the cursor just left the inset?
1199 bool badcursor = false;
1200 if (&cursor_.inset() != &cur.inset())
1201 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1203 // do the dEPM magic if needed
1204 // FIXME: move this to InsetText::notifyCursorLeaves?
1205 if (!badcursor && cursor_.inTexted())
1206 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1209 cursor_.clearSelection();
1210 cursor_.setTargetX();
1216 void BufferView::putSelectionAt(DocIterator const & cur,
1217 int length, bool backwards)
1219 cursor_.clearSelection();
1225 cursor_.pos() += length;
1226 cursor_.setSelection(cursor_, -length);
1228 cursor_.setSelection(cursor_, length);
1233 LCursor & BufferView::cursor()
1239 LCursor const & BufferView::cursor() const
1245 lyx::pit_type BufferView::anchor_ref() const
1251 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1253 return metrics_info_;
1257 void BufferView::updateMetrics(bool singlepar)
1259 // Remove old position cache
1261 LyXText & buftext = buffer_->text();
1262 lyx::pit_type size = int(buftext.paragraphs().size());
1264 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1265 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1269 lyx::pit_type const pit = anchor_ref_;
1272 size_t const npit = buftext.paragraphs().size();
1274 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1275 // the (main text, not inset!) paragraph containing the cursor.
1276 // (if this paragraph contains insets etc., rebreaking will
1277 // recursively descend)
1278 if (!singlepar || pit == cursor_.bottom().pit())
1279 buftext.redoParagraph(pit);
1280 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1282 // Redo paragraphs above anchor if necessary; again, in Single Par
1283 // mode, only if we encounter the (main text) one having the cursor.
1285 while (y1 > 0 && pit1 > 0) {
1286 y1 -= buftext.getPar(pit1).ascent();
1288 if (!singlepar || pit1 == cursor_.bottom().pit())
1289 buftext.redoParagraph(pit1);
1290 y1 -= buftext.getPar(pit1).descent();
1294 // Take care of ascent of first line
1295 y1 -= buftext.getPar(pit1).ascent();
1297 // Normalize anchor for next time
1301 // Grey at the beginning is ugly
1302 if (pit1 == 0 && y1 > 0) {
1308 // Redo paragraphs below the anchor if necessary. Single par mode:
1309 // only the one containing the cursor if encountered.
1311 while (y2 < height_ && pit2 < int(npit) - 1) {
1312 y2 += buftext.getPar(pit2).descent();
1314 if (!singlepar || pit2 == cursor_.bottom().pit())
1315 buftext.redoParagraph(pit2);
1316 y2 += buftext.getPar(pit2).ascent();
1319 // Take care of descent of last line
1320 y2 += buftext.getPar(pit2).descent();
1322 // The coordinates of all these paragraphs are correct, cache them
1324 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[&buftext];
1325 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1326 Paragraph const & par = buftext.getPar(pit);
1328 parPos[pit] = Point(0, y);
1329 if (singlepar && pit == cursor_.bottom().pit()) {
1330 // In Single Paragraph mode, collect here the
1331 // y1 and y2 of the (one) paragraph the cursor is in
1332 y1 = y - par.ascent();
1333 y2 = y + par.descent();
1339 // collect cursor paragraph iter bounds
1340 pit1 = cursor_.bottom().pit();
1341 pit2 = cursor_.bottom().pit();
1344 lyxerr[Debug::DEBUG]
1345 << BOOST_CURRENT_FUNCTION
1348 << " pit1: " << pit1
1349 << " pit2: " << pit2
1350 << " npit: " << npit
1351 << " singlepar: " << singlepar
1355 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1359 void BufferView::menuInsertLyXFile(string const & filenm)
1361 BOOST_ASSERT(cursor_.inTexted());
1362 string filename = filenm;
1364 if (filename.empty()) {
1365 // Launch a file browser
1366 string initpath = lyxrc.document_path;
1369 string const trypath = buffer_->filePath();
1370 // If directory is writeable, use this as default.
1371 if (isDirWriteable(trypath))
1375 FileDialog fileDlg(lyx::to_utf8(_("Select LyX document to insert")),
1377 make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
1378 string(lyxrc.document_path)),
1379 make_pair(string(lyx::to_utf8(_("Examples|#E#e"))),
1380 string(addPath(package().system_support(), "examples"))));
1382 FileDialog::Result result =
1383 fileDlg.open(initpath,
1384 FileFilterList(lyx::to_utf8(_("LyX Documents (*.lyx)"))),
1387 if (result.first == FileDialog::Later)
1390 filename = result.second;
1392 // check selected filename
1393 if (filename.empty()) {
1394 // emit message signal.
1395 message(_("Canceled."));
1400 // Get absolute path of file and add ".lyx"
1401 // to the filename if necessary
1402 filename = fileSearch(string(), filename, "lyx");
1404 docstring const disp_fn = makeDisplayPath(filename);
1405 // emit message signal.
1406 message(bformat(_("Inserting document %1$s..."), disp_fn));
1409 Buffer buf("", false);
1410 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
1411 ErrorList & el = buffer_->errorList("Parse");
1412 // Copy the inserted document error list into the current buffer one.
1413 el = buf.errorList("Parse");
1414 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
1415 buf.params().textclass, el);
1416 res = _("Document %1$s inserted.");
1418 res = _("Could not insert document %1$s");
1420 // emit message signal.
1421 message(bformat(res, disp_fn));
1422 buffer_->errors("Parse");
1427 void BufferView::trackChanges()
1429 bool const tracking = buffer_->params().tracking_changes;
1432 for_each(buffer_->par_iterator_begin(),
1433 buffer_->par_iterator_end(),
1434 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
1435 buffer_->params().tracking_changes = true;
1437 // We cannot allow undos beyond the freeze point
1438 buffer_->undostack().clear();
1440 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
1441 if (lyx::find::findNextChange(this)) {
1442 showDialog("changes");
1446 for_each(buffer_->par_iterator_begin(),
1447 buffer_->par_iterator_end(),
1448 mem_fun_ref(&Paragraph::untrackChanges));
1450 buffer_->params().tracking_changes = false;
1453 buffer_->redostack().clear();