3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
59 #include "TexStream.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
64 #include "VCBackend.h"
66 #include "WordLangTuple.h"
69 #include "insets/InsetBibitem.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetText.h"
75 #include "mathed/InsetMathHull.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include "support/bind.h"
107 #include "support/shared_ptr.h"
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 398; // uwestoehr: support for \mathscr
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
150 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
161 /// search for macro in local (buffer) table or in children
162 MacroData const * getBufferMacro(docstring const & name,
163 DocIterator const & pos) const;
165 /// Update macro table starting with position of it \param it in some
167 void updateMacros(DocIterator & it, DocIterator & scope,
168 bool record_docits = false);
170 void setLabel(ParIterator & it, UpdateType utype) const;
172 void collectRelatives(BufferSet & bufs) const;
174 /** If we have branches that use the file suffix
175 feature, return the file name with suffix appended.
177 support::FileName exportFileName() const;
184 mutable TexRow texrow;
186 /// need to regenerate .tex?
190 mutable bool lyx_clean;
192 /// is autosave needed?
193 mutable bool bak_clean;
195 /// is this a unnamed file (New...)?
201 /// name of the file the buffer is associated with.
204 /** Set to true only when the file is fully loaded.
205 * Used to prevent the premature generation of previews
206 * and by the citation inset.
208 bool file_fully_loaded;
211 mutable TocBackend toc_backend;
214 typedef pair<DocIterator, MacroData> ScopeMacro;
215 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
216 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
217 /// map from the macro name to the position map,
218 /// which maps the macro definition position to the scope and the MacroData.
219 NamePositionScopeMacroMap macros;
220 /// This seem to change the way Buffer::getMacro() works
221 mutable bool macro_lock;
223 /// positions of child buffers in the buffer
224 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
225 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
226 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
227 /// position of children buffers in this buffer
228 BufferPositionMap children_positions;
229 /// map from children inclusion positions to their scope and their buffer
230 PositionScopeBufferMap position_to_children;
232 /// Container for all sort of Buffer dependant errors.
233 map<string, ErrorList> errorLists;
235 /// timestamp and checksum used to test if the file has been externally
236 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
238 unsigned long checksum_;
241 frontend::WorkAreaManager * wa_;
243 frontend::GuiBufferDelegate * gui_;
248 /// A cache for the bibfiles (including bibfiles of loaded child
249 /// documents), needed for appropriate update of natbib labels.
250 mutable support::FileNameList bibfiles_cache_;
252 // FIXME The caching mechanism could be improved. At present, we have a
253 // cache for each Buffer, that caches all the bibliography info for that
254 // Buffer. A more efficient solution would be to have a global cache per
255 // file, and then to construct the Buffer's bibinfo from that.
256 /// A cache for bibliography info
257 mutable BiblioInfo bibinfo_;
258 /// whether the bibinfo cache is valid
259 bool bibinfo_cache_valid_;
260 /// Cache of timestamps of .bib files
261 map<FileName, time_t> bibfile_status_;
263 mutable RefCache ref_cache_;
265 /// our Text that should be wrapped in an InsetText
268 /// This is here to force the test to be done whenever parent_buffer
270 Buffer const * parent() const {
271 // if parent_buffer is not loaded, then it has been unloaded,
272 // which means that parent_buffer is an invalid pointer. So we
273 // set it to null in that case.
274 // however, the BufferList doesn't know about cloned buffers, so
275 // they will always be regarded as unloaded. in that case, we hope
277 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
279 return parent_buffer;
282 void setParent(Buffer const * pb) {
284 && parent_buffer && pb && parent_buffer != pb)
285 LYXERR0("Warning: a buffer should not have two parents!");
289 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
290 /// This one is useful for preview detached in a thread.
291 Buffer const * cloned_buffer_;
294 /// So we can force access via the accessors.
295 mutable Buffer const * parent_buffer;
300 /// Creates the per buffer temporary directory
301 static FileName createBufferTmpDir()
304 // We are in our own directory. Why bother to mangle name?
305 // In fact I wrote this code to circumvent a problematic behaviour
306 // (bug?) of EMX mkstemp().
307 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
308 convert<string>(count++));
310 if (!tmpfl.createDirectory(0777)) {
311 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
312 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
313 from_utf8(tmpfl.absFileName())));
319 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
320 Buffer const * cloned_buffer)
321 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
322 read_only(readonly_), filename(file), file_fully_loaded(false),
323 toc_backend(owner), macro_lock(false), timestamp_(0),
324 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
325 cloned_buffer_(cloned_buffer), parent_buffer(0)
327 if (!cloned_buffer_) {
328 temppath = createBufferTmpDir();
329 lyxvc.setBuffer(owner_);
331 wa_ = new frontend::WorkAreaManager;
334 temppath = cloned_buffer_->d->temppath;
335 file_fully_loaded = true;
336 params = cloned_buffer_->d->params;
337 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
338 bibinfo_ = cloned_buffer_->d->bibinfo_;
339 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
340 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
344 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
345 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
347 LYXERR(Debug::INFO, "Buffer::Buffer()");
349 d->inset = new InsetText(*cloned_buffer->d->inset);
350 d->inset->setBuffer(*this);
351 // FIXME: optimize this loop somewhat, maybe by creating a new
352 // general recursive Inset::setId().
353 DocIterator it = doc_iterator_begin(this);
354 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
355 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
356 it.paragraph().setId(cloned_it.paragraph().id());
358 d->inset = new InsetText(this);
359 d->inset->setAutoBreakRows(true);
360 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
366 LYXERR(Debug::INFO, "Buffer::~Buffer()");
367 // here the buffer should take care that it is
368 // saved properly, before it goes into the void.
370 // GuiView already destroyed
374 // No need to do additional cleanups for internal buffer.
379 // loop over children
380 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
381 Impl::BufferPositionMap::iterator end = d->children_positions.end();
382 for (; it != end; ++it) {
383 Buffer * child = const_cast<Buffer *>(it->first);
384 if (d->cloned_buffer_)
386 // The child buffer might have been closed already.
387 else if (theBufferList().isLoaded(child))
388 theBufferList().releaseChild(this, child);
392 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
393 msg += emergencyWrite();
394 Alert::warning(_("Attempting to close changed document!"), msg);
397 // clear references to children in macro tables
398 d->children_positions.clear();
399 d->position_to_children.clear();
401 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
402 Alert::warning(_("Could not remove temporary directory"),
403 bformat(_("Could not remove the temporary directory %1$s"),
404 from_utf8(d->temppath.absFileName())));
407 // Remove any previewed LaTeX snippets associated with this buffer.
409 thePreviews().removeLoader(*this);
415 Buffer * Buffer::clone() const
417 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
418 buffer_clone->d->macro_lock = true;
419 buffer_clone->d->children_positions.clear();
420 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
421 // math macro caches need to be rethought and simplified.
422 // I am not sure wether we should handle Buffer cloning here or in BufferList.
423 // Right now BufferList knows nothing about buffer clones.
424 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
425 Impl::BufferPositionMap::iterator end = d->children_positions.end();
426 for (; it != end; ++it) {
427 DocIterator dit = it->second.clone(buffer_clone);
428 dit.setBuffer(buffer_clone);
429 Buffer * child = const_cast<Buffer *>(it->first);
430 Buffer * child_clone = child->clone();
431 Inset * inset = dit.nextInset();
432 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
433 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
434 inset_inc->setChildBuffer(child_clone);
435 child_clone->d->setParent(buffer_clone);
436 buffer_clone->setChild(dit, child_clone);
438 buffer_clone->d->macro_lock = false;
443 bool Buffer::isClone() const
445 return d->cloned_buffer_;
449 void Buffer::changed(bool update_metrics) const
452 d->wa_->redrawAll(update_metrics);
456 frontend::WorkAreaManager & Buffer::workAreaManager() const
458 LASSERT(d->wa_, /**/);
463 Text & Buffer::text() const
465 return d->inset->text();
469 Inset & Buffer::inset() const
475 BufferParams & Buffer::params()
481 BufferParams const & Buffer::params() const
487 ParagraphList & Buffer::paragraphs()
489 return text().paragraphs();
493 ParagraphList const & Buffer::paragraphs() const
495 return text().paragraphs();
499 LyXVC & Buffer::lyxvc()
505 LyXVC const & Buffer::lyxvc() const
511 string const Buffer::temppath() const
513 return d->temppath.absFileName();
517 TexRow & Buffer::texrow()
523 TexRow const & Buffer::texrow() const
529 TocBackend & Buffer::tocBackend() const
531 return d->toc_backend;
535 Undo & Buffer::undo()
541 void Buffer::setChild(DocIterator const & dit, Buffer * child)
543 d->children_positions[child] = dit;
547 string Buffer::latexName(bool const no_path) const
549 FileName latex_name =
550 makeLatexName(d->exportFileName());
551 return no_path ? latex_name.onlyFileName()
552 : latex_name.absFileName();
556 FileName Buffer::Impl::exportFileName() const
558 docstring const branch_suffix =
559 params.branchlist().getFileNameSuffix();
560 if (branch_suffix.empty())
563 string const name = filename.onlyFileNameWithoutExt()
564 + to_utf8(branch_suffix);
565 FileName res(filename.onlyPath().absFileName() + "/" + name);
566 res.changeExtension(filename.extension());
572 string Buffer::logName(LogType * type) const
574 string const filename = latexName(false);
576 if (filename.empty()) {
582 string const path = temppath();
584 FileName const fname(addName(temppath(),
585 onlyFileName(changeExtension(filename,
588 // FIXME: how do we know this is the name of the build log?
589 FileName const bname(
590 addName(path, onlyFileName(
591 changeExtension(filename,
592 formats.extension(bufferFormat()) + ".out"))));
594 // Also consider the master buffer log file
595 FileName masterfname = fname;
597 if (masterBuffer() != this) {
598 string const mlogfile = masterBuffer()->logName(&mtype);
599 masterfname = FileName(mlogfile);
602 // If no Latex log or Build log is newer, show Build log
603 if (bname.exists() &&
604 ((!fname.exists() && !masterfname.exists())
605 || (fname.lastModified() < bname.lastModified()
606 && masterfname.lastModified() < bname.lastModified()))) {
607 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
610 return bname.absFileName();
611 // If we have a newer master file log or only a master log, show this
612 } else if (fname != masterfname
613 && (!fname.exists() && (masterfname.exists()
614 || fname.lastModified() < masterfname.lastModified()))) {
615 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
618 return masterfname.absFileName();
620 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
623 return fname.absFileName();
627 void Buffer::setReadonly(bool const flag)
629 if (d->read_only != flag) {
636 void Buffer::setFileName(string const & newfile)
638 d->filename = makeAbsPath(newfile);
639 setReadonly(d->filename.isReadOnly());
644 int Buffer::readHeader(Lexer & lex)
646 int unknown_tokens = 0;
648 int begin_header_line = -1;
650 // Initialize parameters that may be/go lacking in header:
651 params().branchlist().clear();
652 params().preamble.erase();
653 params().options.erase();
654 params().master.erase();
655 params().float_placement.erase();
656 params().paperwidth.erase();
657 params().paperheight.erase();
658 params().leftmargin.erase();
659 params().rightmargin.erase();
660 params().topmargin.erase();
661 params().bottommargin.erase();
662 params().headheight.erase();
663 params().headsep.erase();
664 params().footskip.erase();
665 params().columnsep.erase();
666 params().fontsCJK.erase();
667 params().listings_params.clear();
668 params().clearLayoutModules();
669 params().clearRemovedModules();
670 params().clearIncludedChildren();
671 params().pdfoptions().clear();
672 params().indiceslist().clear();
673 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
674 params().isbackgroundcolor = false;
675 params().fontcolor = lyx::rgbFromHexName("#000000");
676 params().isfontcolor = false;
677 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
678 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
679 params().html_latex_start.clear();
680 params().html_latex_end.clear();
681 params().html_math_img_scale = 1.0;
682 params().output_sync_macro.erase();
684 for (int i = 0; i < 4; ++i) {
685 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
686 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
689 ErrorList & errorList = d->errorLists["Parse"];
698 if (token == "\\end_header")
702 if (token == "\\begin_header") {
703 begin_header_line = line;
707 LYXERR(Debug::PARSER, "Handling document header token: `"
710 string unknown = params().readToken(lex, token, d->filename.onlyPath());
711 if (!unknown.empty()) {
712 if (unknown[0] != '\\' && token == "\\textclass") {
713 Alert::warning(_("Unknown document class"),
714 bformat(_("Using the default document class, because the "
715 "class %1$s is unknown."), from_utf8(unknown)));
718 docstring const s = bformat(_("Unknown token: "
722 errorList.push_back(ErrorItem(_("Document header error"),
727 if (begin_header_line) {
728 docstring const s = _("\\begin_header is missing");
729 errorList.push_back(ErrorItem(_("Document header error"),
733 params().makeDocumentClass();
735 return unknown_tokens;
740 // changed to be public and have one parameter
741 // Returns true if "\end_document" is not read (Asger)
742 bool Buffer::readDocument(Lexer & lex)
744 ErrorList & errorList = d->errorLists["Parse"];
747 if (!lex.checkFor("\\begin_document")) {
748 docstring const s = _("\\begin_document is missing");
749 errorList.push_back(ErrorItem(_("Document header error"),
753 // we are reading in a brand new document
754 LASSERT(paragraphs().empty(), /**/);
758 if (params().outputChanges) {
759 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
760 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
761 LaTeXFeatures::isAvailable("xcolor");
763 if (!dvipost && !xcolorulem) {
764 Alert::warning(_("Changes not shown in LaTeX output"),
765 _("Changes will not be highlighted in LaTeX output, "
766 "because neither dvipost nor xcolor/ulem are installed.\n"
767 "Please install these packages or redefine "
768 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
769 } else if (!xcolorulem) {
770 Alert::warning(_("Changes not shown in LaTeX output"),
771 _("Changes will not be highlighted in LaTeX output "
772 "when using pdflatex, because xcolor and ulem are not installed.\n"
773 "Please install both packages or redefine "
774 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
778 if (!params().master.empty()) {
779 FileName const master_file = makeAbsPath(params().master,
780 onlyPath(absFileName()));
781 if (isLyXFileName(master_file.absFileName())) {
783 checkAndLoadLyXFile(master_file, true);
785 // necessary e.g. after a reload
786 // to re-register the child (bug 5873)
787 // FIXME: clean up updateMacros (here, only
788 // child registering is needed).
789 master->updateMacros();
790 // set master as master buffer, but only
791 // if we are a real child
792 if (master->isChild(this))
794 // if the master is not fully loaded
795 // it is probably just loading this
796 // child. No warning needed then.
797 else if (master->isFullyLoaded())
798 LYXERR0("The master '"
800 << "' assigned to this document ("
802 << ") does not include "
803 "this document. Ignoring the master assignment.");
808 // assure we have a default index
809 params().indiceslist().addDefault(B_("Index"));
812 bool const res = text().read(lex, errorList, d->inset);
816 updateMacroInstances();
821 bool Buffer::readString(string const & s)
823 params().compressed = false;
825 // remove dummy empty par
826 paragraphs().clear();
830 FileName const name = FileName::tempName("Buffer_readString");
831 switch (readFile(lex, name, true)) {
835 // We need to call lyx2lyx, so write the input to a file
836 ofstream os(name.toFilesystemEncoding().c_str());
839 return readFile(name);
849 bool Buffer::readFile(FileName const & filename)
851 FileName fname(filename);
853 params().compressed = fname.isZippedFile();
855 // remove dummy empty par
856 paragraphs().clear();
859 if (readFile(lex, fname) != success)
866 bool Buffer::isFullyLoaded() const
868 return d->file_fully_loaded;
872 void Buffer::setFullyLoaded(bool value)
874 d->file_fully_loaded = value;
878 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
881 LASSERT(!filename.empty(), /**/);
883 // the first (non-comment) token _must_ be...
884 if (!lex.checkFor("\\lyxformat")) {
885 Alert::error(_("Document format failure"),
886 bformat(_("%1$s is not a readable LyX document."),
887 from_utf8(filename.absFileName())));
893 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
894 // if present remove ".," from string.
895 size_t dot = tmp_format.find_first_of(".,");
896 //lyxerr << " dot found at " << dot << endl;
897 if (dot != string::npos)
898 tmp_format.erase(dot, 1);
899 int const file_format = convert<int>(tmp_format);
900 //lyxerr << "format: " << file_format << endl;
902 // save timestamp and checksum of the original disk file, making sure
903 // to not overwrite them with those of the file created in the tempdir
904 // when it has to be converted to the current format.
906 // Save the timestamp and checksum of disk file. If filename is an
907 // emergency file, save the timestamp and checksum of the original lyx file
908 // because isExternallyModified will check for this file. (BUG4193)
909 string diskfile = filename.absFileName();
910 if (suffixIs(diskfile, ".emergency"))
911 diskfile = diskfile.substr(0, diskfile.size() - 10);
912 saveCheckSum(FileName(diskfile));
915 if (file_format != LYX_FORMAT) {
918 // lyx2lyx would fail
921 FileName const tmpfile = FileName::tempName("Buffer_readFile");
922 if (tmpfile.empty()) {
923 Alert::error(_("Conversion failed"),
924 bformat(_("%1$s is from a different"
925 " version of LyX, but a temporary"
926 " file for converting it could"
928 from_utf8(filename.absFileName())));
931 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
932 if (lyx2lyx.empty()) {
933 Alert::error(_("Conversion script not found"),
934 bformat(_("%1$s is from a different"
935 " version of LyX, but the"
936 " conversion script lyx2lyx"
937 " could not be found."),
938 from_utf8(filename.absFileName())));
941 ostringstream command;
942 command << os::python()
943 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
944 << " -t " << convert<string>(LYX_FORMAT)
945 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
946 << ' ' << quoteName(filename.toSafeFilesystemEncoding());
947 string const command_str = command.str();
949 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
951 cmd_ret const ret = runCommand(command_str);
952 if (ret.first != 0) {
953 if (file_format < LYX_FORMAT)
954 Alert::error(_("Conversion script failed"),
955 bformat(_("%1$s is from an older version"
956 " of LyX, but the lyx2lyx script"
957 " failed to convert it."),
958 from_utf8(filename.absFileName())));
960 Alert::error(_("Conversion script failed"),
961 bformat(_("%1$s is from a newer version"
962 " of LyX and cannot be converted by the"
964 from_utf8(filename.absFileName())));
967 bool const ret = readFile(tmpfile);
968 // Do stuff with tmpfile name and buffer name here.
969 return ret ? success : failure;
974 if (readDocument(lex)) {
975 Alert::error(_("Document format failure"),
976 bformat(_("%1$s ended unexpectedly, which means"
977 " that it is probably corrupted."),
978 from_utf8(filename.absFileName())));
982 d->file_fully_loaded = true;
987 // Should probably be moved to somewhere else: BufferView? GuiView?
988 bool Buffer::save() const
990 // ask if the disk file has been externally modified (use checksum method)
991 if (fileName().exists() && isExternallyModified(checksum_method)) {
992 docstring const file = makeDisplayPath(absFileName(), 20);
993 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
994 "you want to overwrite this file?"), file);
995 int const ret = Alert::prompt(_("Overwrite modified file?"),
996 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1001 // We don't need autosaves in the immediate future. (Asger)
1002 resetAutosaveTimers();
1004 FileName backupName;
1005 bool madeBackup = false;
1007 // make a backup if the file already exists
1008 if (lyxrc.make_backup && fileName().exists()) {
1009 backupName = FileName(absFileName() + '~');
1010 if (!lyxrc.backupdir_path.empty()) {
1011 string const mangledName =
1012 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1013 backupName = FileName(addName(lyxrc.backupdir_path,
1016 // do not copy because of #6587
1017 if (fileName().moveTo(backupName)) {
1020 Alert::error(_("Backup failure"),
1021 bformat(_("Cannot create backup file %1$s.\n"
1022 "Please check whether the directory exists and is writeable."),
1023 from_utf8(backupName.absFileName())));
1024 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1028 if (writeFile(d->filename)) {
1032 // Saving failed, so backup is not backup
1034 backupName.moveTo(d->filename);
1040 bool Buffer::writeFile(FileName const & fname) const
1042 if (d->read_only && fname == d->filename)
1045 bool retval = false;
1047 docstring const str = bformat(_("Saving document %1$s..."),
1048 makeDisplayPath(fname.absFileName()));
1051 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1053 if (params().compressed) {
1054 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1055 retval = ofs && write(ofs);
1057 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1058 retval = ofs && write(ofs);
1062 message(str + _(" could not write file!"));
1067 // removeAutosaveFile();
1069 saveCheckSum(d->filename);
1070 message(str + _(" done."));
1076 docstring Buffer::emergencyWrite()
1078 // No need to save if the buffer has not changed.
1082 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1084 docstring user_message = bformat(
1085 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1087 // We try to save three places:
1088 // 1) Same place as document. Unless it is an unnamed doc.
1090 string s = absFileName();
1093 if (writeFile(FileName(s))) {
1095 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1096 return user_message;
1098 user_message += _(" Save failed! Trying again...\n");
1102 // 2) In HOME directory.
1103 string s = addName(package().home_dir().absFileName(), absFileName());
1105 lyxerr << ' ' << s << endl;
1106 if (writeFile(FileName(s))) {
1108 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1109 return user_message;
1112 user_message += _(" Save failed! Trying yet again...\n");
1114 // 3) In "/tmp" directory.
1115 // MakeAbsPath to prepend the current
1116 // drive letter on OS/2
1117 s = addName(package().temp_dir().absFileName(), absFileName());
1119 lyxerr << ' ' << s << endl;
1120 if (writeFile(FileName(s))) {
1122 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1123 return user_message;
1126 user_message += _(" Save failed! Bummer. Document is lost.");
1129 return user_message;
1133 bool Buffer::write(ostream & ofs) const
1136 // Use the standard "C" locale for file output.
1137 ofs.imbue(locale::classic());
1140 // The top of the file should not be written by params().
1142 // write out a comment in the top of the file
1143 ofs << "#LyX " << lyx_version
1144 << " created this file. For more info see http://www.lyx.org/\n"
1145 << "\\lyxformat " << LYX_FORMAT << "\n"
1146 << "\\begin_document\n";
1148 /// For each author, set 'used' to true if there is a change
1149 /// by this author in the document; otherwise set it to 'false'.
1150 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1151 AuthorList::Authors::const_iterator a_end = params().authors().end();
1152 for (; a_it != a_end; ++a_it)
1153 a_it->setUsed(false);
1155 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1156 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1157 for ( ; it != end; ++it)
1158 it->checkAuthors(params().authors());
1160 // now write out the buffer parameters.
1161 ofs << "\\begin_header\n";
1162 params().writeFile(ofs);
1163 ofs << "\\end_header\n";
1166 ofs << "\n\\begin_body\n";
1168 ofs << "\n\\end_body\n";
1170 // Write marker that shows file is complete
1171 ofs << "\\end_document" << endl;
1173 // Shouldn't really be needed....
1176 // how to check if close went ok?
1177 // Following is an attempt... (BE 20001011)
1179 // good() returns false if any error occured, including some
1180 // formatting error.
1181 // bad() returns true if something bad happened in the buffer,
1182 // which should include file system full errors.
1187 lyxerr << "File was not closed properly." << endl;
1194 bool Buffer::makeLaTeXFile(FileName const & fname,
1195 string const & original_path,
1196 OutputParams const & runparams_in,
1197 bool output_preamble, bool output_body) const
1199 OutputParams runparams = runparams_in;
1200 if (params().useXetex)
1201 runparams.flavor = OutputParams::XETEX;
1203 string const encoding = runparams.encoding->iconvName();
1204 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1207 try { ofs.reset(encoding); }
1208 catch (iconv_codecvt_facet_exception & e) {
1209 lyxerr << "Caught iconv exception: " << e.what() << endl;
1210 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1211 "verify that the support software for your encoding (%1$s) is "
1212 "properly installed"), from_ascii(encoding)));
1215 if (!openFileWrite(ofs, fname))
1218 //TexStream ts(ofs.rdbuf(), &texrow());
1219 ErrorList & errorList = d->errorLists["Export"];
1221 bool failed_export = false;
1224 writeLaTeXSource(ofs, original_path,
1225 runparams, output_preamble, output_body);
1227 catch (EncodingException & e) {
1228 odocstringstream ods;
1229 ods.put(e.failed_char);
1231 oss << "0x" << hex << e.failed_char << dec;
1232 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1233 " (code point %2$s)"),
1234 ods.str(), from_utf8(oss.str()));
1235 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1236 "representable in the chosen encoding.\n"
1237 "Changing the document encoding to utf8 could help."),
1238 e.par_id, e.pos, e.pos + 1));
1239 failed_export = true;
1241 catch (iconv_codecvt_facet_exception & e) {
1242 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1243 _(e.what()), -1, 0, 0));
1244 failed_export = true;
1246 catch (exception const & e) {
1247 errorList.push_back(ErrorItem(_("conversion failed"),
1248 _(e.what()), -1, 0, 0));
1249 failed_export = true;
1252 lyxerr << "Caught some really weird exception..." << endl;
1258 failed_export = true;
1259 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1263 return !failed_export;
1267 void Buffer::writeLaTeXSource(odocstream & os,
1268 string const & original_path,
1269 OutputParams const & runparams_in,
1270 bool const output_preamble, bool const output_body) const
1272 // The child documents, if any, shall be already loaded at this point.
1274 OutputParams runparams = runparams_in;
1276 // Classify the unicode characters appearing in math insets
1277 Encodings::initUnicodeMath(*this);
1279 // validate the buffer.
1280 LYXERR(Debug::LATEX, " Validating buffer...");
1281 LaTeXFeatures features(*this, params(), runparams);
1283 LYXERR(Debug::LATEX, " Buffer validation done.");
1285 // The starting paragraph of the coming rows is the
1286 // first paragraph of the document. (Asger)
1287 if (output_preamble && runparams.nice) {
1288 os << "%% LyX " << lyx_version << " created this file. "
1289 "For more info, see http://www.lyx.org/.\n"
1290 "%% Do not edit unless you really know what "
1292 d->texrow.newline();
1293 d->texrow.newline();
1295 LYXERR(Debug::INFO, "lyx document header finished");
1297 // Don't move this behind the parent_buffer=0 code below,
1298 // because then the macros will not get the right "redefinition"
1299 // flag as they don't see the parent macros which are output before.
1302 // fold macros if possible, still with parent buffer as the
1303 // macros will be put in the prefix anyway.
1304 updateMacroInstances();
1306 // There are a few differences between nice LaTeX and usual files:
1307 // usual is \batchmode and has a
1308 // special input@path to allow the including of figures
1309 // with either \input or \includegraphics (what figinsets do).
1310 // input@path is set when the actual parameter
1311 // original_path is set. This is done for usual tex-file, but not
1312 // for nice-latex-file. (Matthias 250696)
1313 // Note that input@path is only needed for something the user does
1314 // in the preamble, included .tex files or ERT, files included by
1315 // LyX work without it.
1316 if (output_preamble) {
1317 if (!runparams.nice) {
1318 // code for usual, NOT nice-latex-file
1319 os << "\\batchmode\n"; // changed
1320 // from \nonstopmode
1321 d->texrow.newline();
1323 if (!original_path.empty()) {
1325 // We don't know the encoding of inputpath
1326 docstring const inputpath = from_utf8(support::latex_path(original_path));
1327 docstring uncodable_glyphs;
1328 Encoding const * const enc = runparams.encoding;
1330 for (size_t n = 0; n < inputpath.size(); ++n) {
1331 docstring const glyph =
1332 docstring(1, inputpath[n]);
1333 if (enc->latexChar(inputpath[n], true) != glyph) {
1334 LYXERR0("Uncodable character '"
1336 << "' in input path!");
1337 uncodable_glyphs += glyph;
1342 // warn user if we found uncodable glyphs.
1343 if (!uncodable_glyphs.empty()) {
1344 frontend::Alert::warning(_("Uncodable character in file path"),
1345 support::bformat(_("The path of your document\n"
1347 "contains glyphs that are unknown in the\n"
1348 "current document encoding (namely %2$s).\n"
1349 "This will likely result in incomplete output.\n\n"
1350 "Choose an appropriate document encoding (such as utf8)\n"
1351 "or change the file path name."), inputpath, uncodable_glyphs));
1353 os << "\\makeatletter\n"
1354 << "\\def\\input@path{{"
1355 << inputpath << "/}}\n"
1356 << "\\makeatother\n";
1357 d->texrow.newline();
1358 d->texrow.newline();
1359 d->texrow.newline();
1363 // get parent macros (if this buffer has a parent) which will be
1364 // written at the document begin further down.
1365 MacroSet parentMacros;
1366 listParentMacros(parentMacros, features);
1368 // Write the preamble
1369 runparams.use_babel = params().writeLaTeX(os, features,
1371 d->filename.onlyPath());
1373 runparams.use_japanese = features.isRequired("japanese");
1379 os << "\\begin{document}\n";
1380 d->texrow.newline();
1382 // output the parent macros
1383 MacroSet::iterator it = parentMacros.begin();
1384 MacroSet::iterator end = parentMacros.end();
1385 for (; it != end; ++it) {
1386 int num_lines = (*it)->write(os, true);
1387 d->texrow.newlines(num_lines);
1390 } // output_preamble
1392 d->texrow.start(paragraphs().begin()->id(), 0);
1394 LYXERR(Debug::INFO, "preamble finished, now the body.");
1396 // if we are doing a real file with body, even if this is the
1397 // child of some other buffer, let's cut the link here.
1398 // This happens for example if only a child document is printed.
1399 Buffer const * save_parent = 0;
1400 if (output_preamble) {
1401 save_parent = d->parent();
1406 latexParagraphs(*this, text(), os, d->texrow, runparams);
1408 // Restore the parenthood if needed
1409 if (output_preamble)
1410 d->setParent(save_parent);
1412 // add this just in case after all the paragraphs
1414 d->texrow.newline();
1416 if (output_preamble) {
1417 os << "\\end{document}\n";
1418 d->texrow.newline();
1419 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1421 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1423 runparams_in.encoding = runparams.encoding;
1425 // Just to be sure. (Asger)
1426 d->texrow.newline();
1428 //for (int i = 0; i<d->texrow.rows(); i++) {
1430 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1431 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1434 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1435 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1439 bool Buffer::isLatex() const
1441 return params().documentClass().outputType() == LATEX;
1445 bool Buffer::isLiterate() const
1447 return params().documentClass().outputType() == LITERATE;
1451 bool Buffer::isDocBook() const
1453 return params().documentClass().outputType() == DOCBOOK;
1457 void Buffer::makeDocBookFile(FileName const & fname,
1458 OutputParams const & runparams,
1459 bool const body_only) const
1461 LYXERR(Debug::LATEX, "makeDocBookFile...");
1464 if (!openFileWrite(ofs, fname))
1467 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1471 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1475 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1476 OutputParams const & runparams,
1477 bool const only_body) const
1479 LaTeXFeatures features(*this, params(), runparams);
1484 DocumentClass const & tclass = params().documentClass();
1485 string const top_element = tclass.latexname();
1488 if (runparams.flavor == OutputParams::XML)
1489 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1492 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1495 if (! tclass.class_header().empty())
1496 os << from_ascii(tclass.class_header());
1497 else if (runparams.flavor == OutputParams::XML)
1498 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1499 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1501 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1503 docstring preamble = from_utf8(params().preamble);
1504 if (runparams.flavor != OutputParams::XML ) {
1505 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1506 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1507 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1508 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1511 string const name = runparams.nice
1512 ? changeExtension(absFileName(), ".sgml") : fname;
1513 preamble += features.getIncludedFiles(name);
1514 preamble += features.getLyXSGMLEntities();
1516 if (!preamble.empty()) {
1517 os << "\n [ " << preamble << " ]";
1522 string top = top_element;
1524 if (runparams.flavor == OutputParams::XML)
1525 top += params().language->code();
1527 top += params().language->code().substr(0, 2);
1530 if (!params().options.empty()) {
1532 top += params().options;
1535 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1536 << " file was created by LyX " << lyx_version
1537 << "\n See http://www.lyx.org/ for more information -->\n";
1539 params().documentClass().counters().reset();
1543 sgml::openTag(os, top);
1545 docbookParagraphs(text(), *this, os, runparams);
1546 sgml::closeTag(os, top_element);
1550 void Buffer::makeLyXHTMLFile(FileName const & fname,
1551 OutputParams const & runparams,
1552 bool const body_only) const
1554 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1557 if (!openFileWrite(ofs, fname))
1560 writeLyXHTMLSource(ofs, runparams, body_only);
1564 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1568 void Buffer::writeLyXHTMLSource(odocstream & os,
1569 OutputParams const & runparams,
1570 bool const only_body) const
1572 LaTeXFeatures features(*this, params(), runparams);
1574 updateBuffer(UpdateMaster, OutputUpdate);
1575 checkBibInfoCache();
1576 d->bibinfo_.makeCitationLabels(*this);
1578 updateMacroInstances();
1581 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1582 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n"
1583 // FIXME Language should be set properly.
1584 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1586 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1587 // FIXME Presumably need to set this right
1588 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1590 docstring const & doctitle = features.htmlTitle();
1592 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1595 os << "\n<!-- Text Class Preamble -->\n"
1596 << features.getTClassHTMLPreamble()
1597 << "\n<!-- Premable Snippets -->\n"
1598 << from_utf8(features.getPreambleSnippets());
1600 os << "\n<!-- Layout-provided Styles -->\n";
1601 docstring const styleinfo = features.getTClassHTMLStyles();
1602 if (!styleinfo.empty()) {
1603 os << "<style type='text/css'>\n"
1607 os << "</head>\n<body>\n";
1611 params().documentClass().counters().reset();
1612 xhtmlParagraphs(text(), *this, xs, runparams);
1614 os << "</body>\n</html>\n";
1618 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1619 // Other flags: -wall -v0 -x
1620 int Buffer::runChktex()
1624 // get LaTeX-Filename
1625 FileName const path(temppath());
1626 string const name = addName(path.absFileName(), latexName());
1627 string const org_path = filePath();
1629 PathChanger p(path); // path to LaTeX file
1630 message(_("Running chktex..."));
1632 // Generate the LaTeX file if neccessary
1633 OutputParams runparams(¶ms().encoding());
1634 runparams.flavor = OutputParams::LATEX;
1635 runparams.nice = false;
1636 runparams.linelen = lyxrc.plaintext_linelen;
1637 makeLaTeXFile(FileName(name), org_path, runparams);
1640 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1641 int const res = chktex.run(terr); // run chktex
1644 Alert::error(_("chktex failure"),
1645 _("Could not run chktex successfully."));
1646 } else if (res > 0) {
1647 ErrorList & errlist = d->errorLists["ChkTeX"];
1649 bufferErrors(terr, errlist);
1660 void Buffer::validate(LaTeXFeatures & features) const
1662 params().validate(features);
1666 for_each(paragraphs().begin(), paragraphs().end(),
1667 bind(&Paragraph::validate, _1, ref(features)));
1669 if (lyxerr.debugging(Debug::LATEX)) {
1670 features.showStruct();
1675 void Buffer::getLabelList(vector<docstring> & list) const
1677 // If this is a child document, use the parent's list instead.
1678 Buffer const * const pbuf = d->parent();
1680 pbuf->getLabelList(list);
1685 Toc & toc = d->toc_backend.toc("label");
1686 TocIterator toc_it = toc.begin();
1687 TocIterator end = toc.end();
1688 for (; toc_it != end; ++toc_it) {
1689 if (toc_it->depth() == 0)
1690 list.push_back(toc_it->str());
1695 void Buffer::updateBibfilesCache(UpdateScope scope) const
1697 // If this is a child document, use the parent's cache instead.
1698 Buffer const * const pbuf = d->parent();
1699 if (pbuf && scope != UpdateChildOnly) {
1700 pbuf->updateBibfilesCache();
1704 d->bibfiles_cache_.clear();
1705 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1706 if (it->lyxCode() == BIBTEX_CODE) {
1707 InsetBibtex const & inset =
1708 static_cast<InsetBibtex const &>(*it);
1709 support::FileNameList const bibfiles = inset.getBibFiles();
1710 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1713 } else if (it->lyxCode() == INCLUDE_CODE) {
1714 InsetInclude & inset =
1715 static_cast<InsetInclude &>(*it);
1716 inset.updateBibfilesCache();
1717 support::FileNameList const & bibfiles =
1718 inset.getBibfilesCache();
1719 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1724 // the bibinfo cache is now invalid
1725 d->bibinfo_cache_valid_ = false;
1729 void Buffer::invalidateBibinfoCache()
1731 d->bibinfo_cache_valid_ = false;
1735 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1737 // If this is a child document, use the parent's cache instead.
1738 Buffer const * const pbuf = d->parent();
1739 if (pbuf && scope != UpdateChildOnly)
1740 return pbuf->getBibfilesCache();
1742 // We update the cache when first used instead of at loading time.
1743 if (d->bibfiles_cache_.empty())
1744 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1746 return d->bibfiles_cache_;
1750 BiblioInfo const & Buffer::masterBibInfo() const
1752 // if this is a child document and the parent is already loaded
1753 // use the parent's list instead [ale990412]
1754 Buffer const * const tmp = masterBuffer();
1757 return tmp->masterBibInfo();
1758 return localBibInfo();
1762 BiblioInfo const & Buffer::localBibInfo() const
1768 void Buffer::checkBibInfoCache() const
1770 support::FileNameList const & bibfilesCache = getBibfilesCache();
1771 // compare the cached timestamps with the actual ones.
1772 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1773 support::FileNameList::const_iterator en = bibfilesCache.end();
1774 for (; ei != en; ++ ei) {
1775 time_t lastw = ei->lastModified();
1776 time_t prevw = d->bibfile_status_[*ei];
1777 if (lastw != prevw) {
1778 d->bibinfo_cache_valid_ = false;
1779 d->bibfile_status_[*ei] = lastw;
1783 if (!d->bibinfo_cache_valid_) {
1784 d->bibinfo_.clear();
1785 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1786 it->fillWithBibKeys(d->bibinfo_, it);
1787 d->bibinfo_cache_valid_ = true;
1792 bool Buffer::isDepClean(string const & name) const
1794 DepClean::const_iterator const it = d->dep_clean.find(name);
1795 if (it == d->dep_clean.end())
1801 void Buffer::markDepClean(string const & name)
1803 d->dep_clean[name] = true;
1807 bool Buffer::isExportableFormat(string const & format) const
1809 typedef vector<Format const *> Formats;
1811 formats = exportableFormats(true);
1812 Formats::const_iterator fit = formats.begin();
1813 Formats::const_iterator end = formats.end();
1814 for (; fit != end ; ++fit) {
1815 if ((*fit)->name() == format)
1822 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1825 // FIXME? if there is an Buffer LFUN that can be dispatched even
1826 // if internal, put a switch '(cmd.action)' here.
1832 switch (cmd.action()) {
1834 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1835 flag.setOnOff(isReadonly());
1838 // FIXME: There is need for a command-line import.
1839 //case LFUN_BUFFER_IMPORT:
1841 case LFUN_BUFFER_AUTO_SAVE:
1844 case LFUN_BUFFER_EXPORT_CUSTOM:
1845 // FIXME: Nothing to check here?
1848 case LFUN_BUFFER_EXPORT: {
1849 docstring const arg = cmd.argument();
1850 enable = arg == "custom" || isExportable(to_utf8(arg));
1852 flag.message(bformat(
1853 _("Don't know how to export to format: %1$s"), arg));
1857 case LFUN_BUFFER_CHKTEX:
1858 enable = isLatex() && !lyxrc.chktex_command.empty();
1861 case LFUN_BUILD_PROGRAM:
1862 enable = isExportable("program");
1865 case LFUN_BRANCH_ACTIVATE:
1866 case LFUN_BRANCH_DEACTIVATE: {
1867 BranchList const & branchList = params().branchlist();
1868 docstring const branchName = cmd.argument();
1869 enable = !branchName.empty() && branchList.find(branchName);
1873 case LFUN_BRANCH_ADD:
1874 case LFUN_BRANCHES_RENAME:
1875 case LFUN_BUFFER_PRINT:
1876 // if no Buffer is present, then of course we won't be called!
1879 case LFUN_BUFFER_LANGUAGE:
1880 enable = !isReadonly();
1886 flag.setEnabled(enable);
1891 void Buffer::dispatch(string const & command, DispatchResult & result)
1893 return dispatch(lyxaction.lookupFunc(command), result);
1897 // NOTE We can end up here even if we have no GUI, because we are called
1898 // by LyX::exec to handled command-line requests. So we may need to check
1899 // whether we have a GUI or not. The boolean use_gui holds this information.
1900 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1903 // FIXME? if there is an Buffer LFUN that can be dispatched even
1904 // if internal, put a switch '(cmd.action())' here.
1905 dr.dispatched(false);
1908 string const argument = to_utf8(func.argument());
1909 // We'll set this back to false if need be.
1910 bool dispatched = true;
1911 undo().beginUndoGroup();
1913 switch (func.action()) {
1914 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1915 if (lyxvc().inUse())
1916 lyxvc().toggleReadOnly();
1918 setReadonly(!isReadonly());
1921 case LFUN_BUFFER_EXPORT: {
1922 bool success = doExport(argument, false, false);
1923 dr.setError(!success);
1925 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1930 case LFUN_BUILD_PROGRAM:
1931 doExport("program", true, false);
1934 case LFUN_BUFFER_CHKTEX:
1938 case LFUN_BUFFER_EXPORT_CUSTOM: {
1940 string command = split(argument, format_name, ' ');
1941 Format const * format = formats.getFormat(format_name);
1943 lyxerr << "Format \"" << format_name
1944 << "\" not recognized!"
1949 // The name of the file created by the conversion process
1952 // Output to filename
1953 if (format->name() == "lyx") {
1954 string const latexname = latexName(false);
1955 filename = changeExtension(latexname,
1956 format->extension());
1957 filename = addName(temppath(), filename);
1959 if (!writeFile(FileName(filename)))
1963 doExport(format_name, true, false, filename);
1966 // Substitute $$FName for filename
1967 if (!contains(command, "$$FName"))
1968 command = "( " + command + " ) < $$FName";
1969 command = subst(command, "$$FName", filename);
1971 // Execute the command in the background
1973 call.startscript(Systemcall::DontWait, command);
1977 // FIXME: There is need for a command-line import.
1979 case LFUN_BUFFER_IMPORT:
1984 case LFUN_BUFFER_AUTO_SAVE:
1988 case LFUN_BRANCH_ADD: {
1989 docstring branch_name = func.argument();
1990 if (branch_name.empty()) {
1994 BranchList & branch_list = params().branchlist();
1995 vector<docstring> const branches =
1996 getVectorFromString(branch_name, branch_list.separator());
1998 for (vector<docstring>::const_iterator it = branches.begin();
1999 it != branches.end(); ++it) {
2001 Branch * branch = branch_list.find(branch_name);
2003 LYXERR0("Branch " << branch_name << " already exists.");
2007 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2009 branch_list.add(branch_name);
2010 branch = branch_list.find(branch_name);
2011 string const x11hexname = X11hexname(branch->color());
2012 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2013 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2015 dr.update(Update::Force);
2023 case LFUN_BRANCH_ACTIVATE:
2024 case LFUN_BRANCH_DEACTIVATE: {
2025 BranchList & branchList = params().branchlist();
2026 docstring const branchName = func.argument();
2027 // the case without a branch name is handled elsewhere
2028 if (branchName.empty()) {
2032 Branch * branch = branchList.find(branchName);
2034 LYXERR0("Branch " << branchName << " does not exist.");
2036 docstring const msg =
2037 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2040 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2042 dr.update(Update::Force);
2043 dr.forceBufferUpdate();
2048 case LFUN_BRANCHES_RENAME: {
2049 if (func.argument().empty())
2052 docstring const oldname = from_utf8(func.getArg(0));
2053 docstring const newname = from_utf8(func.getArg(1));
2054 InsetIterator it = inset_iterator_begin(inset());
2055 InsetIterator const end = inset_iterator_end(inset());
2056 bool success = false;
2057 for (; it != end; ++it) {
2058 if (it->lyxCode() == BRANCH_CODE) {
2059 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2060 if (ins.branch() == oldname) {
2061 undo().recordUndo(it);
2062 ins.rename(newname);
2067 if (it->lyxCode() == INCLUDE_CODE) {
2068 // get buffer of external file
2069 InsetInclude const & ins =
2070 static_cast<InsetInclude const &>(*it);
2071 Buffer * child = ins.getChildBuffer();
2074 child->dispatch(func, dr);
2079 dr.update(Update::Force);
2080 dr.forceBufferUpdate();
2085 case LFUN_BUFFER_PRINT: {
2086 // we'll assume there's a problem until we succeed
2088 string target = func.getArg(0);
2089 string target_name = func.getArg(1);
2090 string command = func.getArg(2);
2093 || target_name.empty()
2094 || command.empty()) {
2095 LYXERR0("Unable to parse " << func.argument());
2096 docstring const msg =
2097 bformat(_("Unable to parse \"%1$s\""), func.argument());
2101 if (target != "printer" && target != "file") {
2102 LYXERR0("Unrecognized target \"" << target << '"');
2103 docstring const msg =
2104 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2109 bool const update_unincluded =
2110 params().maintain_unincluded_children
2111 && !params().getIncludedChildren().empty();
2112 if (!doExport("dvi", true, update_unincluded)) {
2113 showPrintError(absFileName());
2114 dr.setMessage(_("Error exporting to DVI."));
2118 // Push directory path.
2119 string const path = temppath();
2120 // Prevent the compiler from optimizing away p
2124 // there are three cases here:
2125 // 1. we print to a file
2126 // 2. we print directly to a printer
2127 // 3. we print using a spool command (print to file first)
2130 string const dviname = changeExtension(latexName(true), "dvi");
2132 if (target == "printer") {
2133 if (!lyxrc.print_spool_command.empty()) {
2134 // case 3: print using a spool
2135 string const psname = changeExtension(dviname,".ps");
2136 command += ' ' + lyxrc.print_to_file
2139 + quoteName(dviname);
2141 string command2 = lyxrc.print_spool_command + ' ';
2142 if (target_name != "default") {
2143 command2 += lyxrc.print_spool_printerprefix
2147 command2 += quoteName(psname);
2149 // If successful, then spool command
2150 res = one.startscript(Systemcall::Wait, command);
2153 // If there's no GUI, we have to wait on this command. Otherwise,
2154 // LyX deletes the temporary directory, and with it the spooled
2155 // file, before it can be printed!!
2156 Systemcall::Starttype stype = use_gui ?
2157 Systemcall::DontWait : Systemcall::Wait;
2158 res = one.startscript(stype, command2);
2161 // case 2: print directly to a printer
2162 if (target_name != "default")
2163 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2165 Systemcall::Starttype stype = use_gui ?
2166 Systemcall::DontWait : Systemcall::Wait;
2167 res = one.startscript(stype, command + quoteName(dviname));
2171 // case 1: print to a file
2172 FileName const filename(makeAbsPath(target_name, filePath()));
2173 FileName const dvifile(makeAbsPath(dviname, path));
2174 if (filename.exists()) {
2175 docstring text = bformat(
2176 _("The file %1$s already exists.\n\n"
2177 "Do you want to overwrite that file?"),
2178 makeDisplayPath(filename.absFileName()));
2179 if (Alert::prompt(_("Overwrite file?"),
2180 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2183 command += ' ' + lyxrc.print_to_file
2184 + quoteName(filename.toFilesystemEncoding())
2186 + quoteName(dvifile.toFilesystemEncoding());
2188 Systemcall::Starttype stype = use_gui ?
2189 Systemcall::DontWait : Systemcall::Wait;
2190 res = one.startscript(stype, command);
2196 dr.setMessage(_("Error running external commands."));
2197 showPrintError(absFileName());
2202 case LFUN_BUFFER_LANGUAGE: {
2203 Language const * oldL = params().language;
2204 Language const * newL = languages.getLanguage(argument);
2205 if (!newL || oldL == newL)
2207 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2208 changeLanguage(oldL, newL);
2209 dr.forceBufferUpdate();
2218 dr.dispatched(dispatched);
2219 undo().endUndoGroup();
2223 void Buffer::changeLanguage(Language const * from, Language const * to)
2225 LASSERT(from, /**/);
2228 for_each(par_iterator_begin(),
2230 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2234 bool Buffer::isMultiLingual() const
2236 ParConstIterator end = par_iterator_end();
2237 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2238 if (it->isMultiLingual(params()))
2245 std::set<Language const *> Buffer::getLanguages() const
2247 std::set<Language const *> languages;
2248 getLanguages(languages);
2253 void Buffer::getLanguages(std::set<Language const *> & languages) const
2255 ParConstIterator end = par_iterator_end();
2256 // add the buffer language, even if it's not actively used
2257 languages.insert(language());
2258 // iterate over the paragraphs
2259 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2260 it->getLanguages(languages);
2262 std::vector<Buffer *> clist = getChildren();
2263 for (vector<Buffer *>::const_iterator cit = clist.begin();
2264 cit != clist.end(); ++cit)
2265 (*cit)->getLanguages(languages);
2269 DocIterator Buffer::getParFromID(int const id) const
2271 Buffer * buf = const_cast<Buffer *>(this);
2273 // John says this is called with id == -1 from undo
2274 lyxerr << "getParFromID(), id: " << id << endl;
2275 return doc_iterator_end(buf);
2278 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2279 if (it.paragraph().id() == id)
2282 return doc_iterator_end(buf);
2286 bool Buffer::hasParWithID(int const id) const
2288 return !getParFromID(id).atEnd();
2292 ParIterator Buffer::par_iterator_begin()
2294 return ParIterator(doc_iterator_begin(this));
2298 ParIterator Buffer::par_iterator_end()
2300 return ParIterator(doc_iterator_end(this));
2304 ParConstIterator Buffer::par_iterator_begin() const
2306 return ParConstIterator(doc_iterator_begin(this));
2310 ParConstIterator Buffer::par_iterator_end() const
2312 return ParConstIterator(doc_iterator_end(this));
2316 Language const * Buffer::language() const
2318 return params().language;
2322 docstring const Buffer::B_(string const & l10n) const
2324 return params().B_(l10n);
2328 bool Buffer::isClean() const
2330 return d->lyx_clean;
2334 bool Buffer::isExternallyModified(CheckMethod method) const
2336 LASSERT(d->filename.exists(), /**/);
2337 // if method == timestamp, check timestamp before checksum
2338 return (method == checksum_method
2339 || d->timestamp_ != d->filename.lastModified())
2340 && d->checksum_ != d->filename.checksum();
2344 void Buffer::saveCheckSum(FileName const & file) const
2346 if (file.exists()) {
2347 d->timestamp_ = file.lastModified();
2348 d->checksum_ = file.checksum();
2350 // in the case of save to a new file.
2357 void Buffer::markClean() const
2359 if (!d->lyx_clean) {
2360 d->lyx_clean = true;
2363 // if the .lyx file has been saved, we don't need an
2365 d->bak_clean = true;
2369 void Buffer::setUnnamed(bool flag)
2375 bool Buffer::isUnnamed() const
2382 /// Don't check unnamed, here: isInternal() is used in
2383 /// newBuffer(), where the unnamed flag has not been set by anyone
2384 /// yet. Also, for an internal buffer, there should be no need for
2385 /// retrieving fileName() nor for checking if it is unnamed or not.
2386 bool Buffer::isInternal() const
2388 return fileName().extension() == "internal";
2392 void Buffer::markDirty()
2395 d->lyx_clean = false;
2398 d->bak_clean = false;
2400 DepClean::iterator it = d->dep_clean.begin();
2401 DepClean::const_iterator const end = d->dep_clean.end();
2403 for (; it != end; ++it)
2408 FileName Buffer::fileName() const
2414 string Buffer::absFileName() const
2416 return d->filename.absFileName();
2420 string Buffer::filePath() const
2422 return d->filename.onlyPath().absFileName() + "/";
2426 bool Buffer::isReadonly() const
2428 return d->read_only;
2432 void Buffer::setParent(Buffer const * buffer)
2434 // Avoids recursive include.
2435 d->setParent(buffer == this ? 0 : buffer);
2440 Buffer const * Buffer::parent() const
2446 void Buffer::Impl::collectRelatives(BufferSet & bufs) const
2448 bufs.insert(owner_);
2450 parent()->d->collectRelatives(bufs);
2452 // loop over children
2453 BufferPositionMap::const_iterator it = children_positions.begin();
2454 BufferPositionMap::const_iterator end = children_positions.end();
2455 for (; it != end; ++it)
2456 bufs.insert(const_cast<Buffer *>(it->first));
2460 std::vector<Buffer const *> Buffer::allRelatives() const
2463 d->collectRelatives(bufs);
2464 BufferSet::iterator it = bufs.begin();
2465 std::vector<Buffer const *> ret;
2466 for (; it != bufs.end(); ++it)
2472 Buffer const * Buffer::masterBuffer() const
2474 Buffer const * const pbuf = d->parent();
2478 return pbuf->masterBuffer();
2482 bool Buffer::isChild(Buffer * child) const
2484 return d->children_positions.find(child) != d->children_positions.end();
2488 DocIterator Buffer::firstChildPosition(Buffer const * child)
2490 Impl::BufferPositionMap::iterator it;
2491 it = d->children_positions.find(child);
2492 if (it == d->children_positions.end())
2493 return DocIterator(this);
2498 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2500 // loop over children
2501 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2502 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2503 for (; it != end; ++it) {
2504 Buffer * child = const_cast<Buffer *>(it->first);
2505 clist.push_back(child);
2506 if (grand_children) {
2507 // there might be grandchildren
2508 vector<Buffer *> glist = child->getChildren();
2509 clist.insert(clist.end(), glist.begin(), glist.end());
2515 vector<Buffer *> Buffer::getChildren(bool grand_children) const
2518 getChildren(v, grand_children);
2523 template<typename M>
2524 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2529 typename M::const_iterator it = m.lower_bound(x);
2530 if (it == m.begin())
2538 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2539 DocIterator const & pos) const
2541 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2543 // if paragraphs have no macro context set, pos will be empty
2547 // we haven't found anything yet
2548 DocIterator bestPos = owner_->par_iterator_begin();
2549 MacroData const * bestData = 0;
2551 // find macro definitions for name
2552 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2553 if (nameIt != macros.end()) {
2554 // find last definition in front of pos or at pos itself
2555 PositionScopeMacroMap::const_iterator it
2556 = greatest_below(nameIt->second, pos);
2557 if (it != nameIt->second.end()) {
2559 // scope ends behind pos?
2560 if (pos < it->second.first) {
2561 // Looks good, remember this. If there
2562 // is no external macro behind this,
2563 // we found the right one already.
2564 bestPos = it->first;
2565 bestData = &it->second.second;
2569 // try previous macro if there is one
2570 if (it == nameIt->second.begin())
2577 // find macros in included files
2578 PositionScopeBufferMap::const_iterator it
2579 = greatest_below(position_to_children, pos);
2580 if (it == position_to_children.end())
2581 // no children before
2585 // do we know something better (i.e. later) already?
2586 if (it->first < bestPos )
2589 // scope ends behind pos?
2590 if (pos < it->second.first) {
2591 // look for macro in external file
2593 MacroData const * data
2594 = it->second.second->getMacro(name, false);
2597 bestPos = it->first;
2603 // try previous file if there is one
2604 if (it == position_to_children.begin())
2609 // return the best macro we have found
2614 MacroData const * Buffer::getMacro(docstring const & name,
2615 DocIterator const & pos, bool global) const
2620 // query buffer macros
2621 MacroData const * data = d->getBufferMacro(name, pos);
2625 // If there is a master buffer, query that
2626 Buffer const * const pbuf = d->parent();
2628 d->macro_lock = true;
2629 MacroData const * macro = pbuf->getMacro(
2630 name, *this, false);
2631 d->macro_lock = false;
2637 data = MacroTable::globalMacros().get(name);
2646 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2648 // set scope end behind the last paragraph
2649 DocIterator scope = par_iterator_begin();
2650 scope.pit() = scope.lastpit() + 1;
2652 return getMacro(name, scope, global);
2656 MacroData const * Buffer::getMacro(docstring const & name,
2657 Buffer const & child, bool global) const
2659 // look where the child buffer is included first
2660 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2661 if (it == d->children_positions.end())
2664 // check for macros at the inclusion position
2665 return getMacro(name, it->second, global);
2669 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope,
2672 pit_type const lastpit = it.lastpit();
2674 // look for macros in each paragraph
2675 while (it.pit() <= lastpit) {
2676 Paragraph & par = it.paragraph();
2678 // iterate over the insets of the current paragraph
2679 InsetList const & insets = par.insetList();
2680 InsetList::const_iterator iit = insets.begin();
2681 InsetList::const_iterator end = insets.end();
2682 for (; iit != end; ++iit) {
2683 it.pos() = iit->pos;
2685 // is it a nested text inset?
2686 if (iit->inset->asInsetText()) {
2687 // Inset needs its own scope?
2688 InsetText const * itext = iit->inset->asInsetText();
2689 bool newScope = itext->isMacroScope();
2691 // scope which ends just behind the inset
2692 DocIterator insetScope = it;
2695 // collect macros in inset
2696 it.push_back(CursorSlice(*iit->inset));
2697 updateMacros(it, newScope ? insetScope : scope);
2702 // is it an external file?
2703 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2704 // get buffer of external file
2705 InsetInclude const & inset =
2706 static_cast<InsetInclude const &>(*iit->inset);
2708 Buffer * child = inset.getChildBuffer();
2713 // register its position, but only when it is
2714 // included first in the buffer
2715 if (children_positions.find(child) ==
2716 children_positions.end())
2717 children_positions[child] = it;
2719 // register child with its scope
2720 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2724 if (record_docits && iit->inset->asInsetMath()) {
2725 InsetMath * im = static_cast<InsetMath *>(iit->inset);
2726 if (im->asHullInset()) {
2727 InsetMathHull * hull = static_cast<InsetMathHull *>(im);
2728 hull->recordLocation(it);
2732 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2736 MathMacroTemplate & macroTemplate =
2737 static_cast<MathMacroTemplate &>(*iit->inset);
2738 MacroContext mc(owner_, it);
2739 macroTemplate.updateToContext(mc);
2742 bool valid = macroTemplate.validMacro();
2743 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2744 // then the BufferView's cursor will be invalid in
2745 // some cases which leads to crashes.
2750 // FIXME (Abdel), I don't understandt why we pass 'it' here
2751 // instead of 'macroTemplate' defined above... is this correct?
2752 macros[macroTemplate.name()][it] =
2753 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2763 void Buffer::updateMacros(bool record_docit) const
2768 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2770 // start with empty table
2772 d->children_positions.clear();
2773 d->position_to_children.clear();
2775 // Iterate over buffer, starting with first paragraph
2776 // The scope must be bigger than any lookup DocIterator
2777 // later. For the global lookup, lastpit+1 is used, hence
2778 // we use lastpit+2 here.
2779 DocIterator it = par_iterator_begin();
2780 DocIterator outerScope = it;
2781 outerScope.pit() = outerScope.lastpit() + 2;
2782 d->updateMacros(it, outerScope, record_docit);
2786 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2788 InsetIterator it = inset_iterator_begin(inset());
2789 InsetIterator const end = inset_iterator_end(inset());
2790 for (; it != end; ++it) {
2791 if (it->lyxCode() == BRANCH_CODE) {
2792 InsetBranch & br = static_cast<InsetBranch &>(*it);
2793 docstring const name = br.branch();
2794 if (!from_master && !params().branchlist().find(name))
2795 result.push_back(name);
2796 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2797 result.push_back(name);
2800 if (it->lyxCode() == INCLUDE_CODE) {
2801 // get buffer of external file
2802 InsetInclude const & ins =
2803 static_cast<InsetInclude const &>(*it);
2804 Buffer * child = ins.getChildBuffer();
2807 child->getUsedBranches(result, true);
2810 // remove duplicates
2815 void Buffer::updateMacroInstances() const
2817 LYXERR(Debug::MACROS, "updateMacroInstances for "
2818 << d->filename.onlyFileName());
2819 DocIterator it = doc_iterator_begin(this);
2821 DocIterator const end = doc_iterator_end(this);
2822 for (; it != end; it.forwardInset()) {
2823 // look for MathData cells in InsetMathNest insets
2824 InsetMath * minset = it.nextInset()->asInsetMath();
2828 // update macro in all cells of the InsetMathNest
2829 DocIterator::idx_type n = minset->nargs();
2830 MacroContext mc = MacroContext(this, it);
2831 for (DocIterator::idx_type i = 0; i < n; ++i) {
2832 MathData & data = minset->cell(i);
2833 data.updateMacros(0, mc);
2839 void Buffer::listMacroNames(MacroNameSet & macros) const
2844 d->macro_lock = true;
2846 // loop over macro names
2847 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2848 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2849 for (; nameIt != nameEnd; ++nameIt)
2850 macros.insert(nameIt->first);
2852 // loop over children
2853 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2854 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2855 for (; it != end; ++it)
2856 it->first->listMacroNames(macros);
2859 Buffer const * const pbuf = d->parent();
2861 pbuf->listMacroNames(macros);
2863 d->macro_lock = false;
2867 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2869 Buffer const * const pbuf = d->parent();
2874 pbuf->listMacroNames(names);
2877 MacroNameSet::iterator it = names.begin();
2878 MacroNameSet::iterator end = names.end();
2879 for (; it != end; ++it) {
2881 MacroData const * data =
2882 pbuf->getMacro(*it, *this, false);
2884 macros.insert(data);
2886 // we cannot access the original MathMacroTemplate anymore
2887 // here to calls validate method. So we do its work here manually.
2888 // FIXME: somehow make the template accessible here.
2889 if (data->optionals() > 0)
2890 features.require("xargs");
2896 Buffer::References & Buffer::references(docstring const & label)
2899 return const_cast<Buffer *>(masterBuffer())->references(label);
2901 RefCache::iterator it = d->ref_cache_.find(label);
2902 if (it != d->ref_cache_.end())
2903 return it->second.second;
2905 static InsetLabel const * dummy_il = 0;
2906 static References const dummy_refs;
2907 it = d->ref_cache_.insert(
2908 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2909 return it->second.second;
2913 Buffer::References const & Buffer::references(docstring const & label) const
2915 return const_cast<Buffer *>(this)->references(label);
2919 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2921 masterBuffer()->d->ref_cache_[label].first = il;
2925 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2927 return masterBuffer()->d->ref_cache_[label].first;
2931 void Buffer::clearReferenceCache() const
2934 d->ref_cache_.clear();
2938 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2941 //FIXME: This does not work for child documents yet.
2942 LASSERT(code == CITE_CODE, /**/);
2943 // Check if the label 'from' appears more than once
2944 vector<docstring> labels;
2946 checkBibInfoCache();
2947 BiblioInfo const & keys = masterBibInfo();
2948 BiblioInfo::const_iterator bit = keys.begin();
2949 BiblioInfo::const_iterator bend = keys.end();
2951 for (; bit != bend; ++bit)
2953 labels.push_back(bit->first);
2956 if (count(labels.begin(), labels.end(), from) > 1)
2959 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2960 if (it->lyxCode() == code) {
2961 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2962 docstring const oldValue = inset.getParam(paramName);
2963 if (oldValue == from)
2964 inset.setParam(paramName, to);
2970 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2971 pit_type par_end, bool full_source) const
2973 OutputParams runparams(¶ms().encoding());
2974 runparams.nice = true;
2975 runparams.flavor = params().useXetex ?
2976 OutputParams::XETEX : OutputParams::LATEX;
2977 runparams.linelen = lyxrc.plaintext_linelen;
2978 // No side effect of file copying and image conversion
2979 runparams.dryrun = true;
2982 os << "% " << _("Preview source code") << "\n\n";
2984 d->texrow.newline();
2985 d->texrow.newline();
2987 writeDocBookSource(os, absFileName(), runparams, false);
2989 // latex or literate
2990 writeLaTeXSource(os, string(), runparams, true, true);
2992 runparams.par_begin = par_begin;
2993 runparams.par_end = par_end;
2994 if (par_begin + 1 == par_end) {
2996 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3000 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3001 convert<docstring>(par_begin),
3002 convert<docstring>(par_end - 1))
3009 // output paragraphs
3011 docbookParagraphs(text(), *this, os, runparams);
3013 // latex or literate
3014 latexParagraphs(*this, text(), os, texrow, runparams);
3019 ErrorList & Buffer::errorList(string const & type) const
3021 static ErrorList emptyErrorList;
3022 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3023 if (it == d->errorLists.end())
3024 return emptyErrorList;
3030 void Buffer::updateTocItem(std::string const & type,
3031 DocIterator const & dit) const
3034 d->gui_->updateTocItem(type, dit);
3038 void Buffer::structureChanged() const
3041 d->gui_->structureChanged();
3045 void Buffer::errors(string const & err, bool from_master) const
3048 d->gui_->errors(err, from_master);
3052 void Buffer::message(docstring const & msg) const
3055 d->gui_->message(msg);
3059 void Buffer::setBusy(bool on) const
3062 d->gui_->setBusy(on);
3066 void Buffer::updateTitles() const
3069 d->wa_->updateTitles();
3073 void Buffer::resetAutosaveTimers() const
3076 d->gui_->resetAutosaveTimers();
3080 bool Buffer::hasGuiDelegate() const
3086 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3095 class AutoSaveBuffer : public ForkedProcess {
3098 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3099 : buffer_(buffer), fname_(fname) {}
3101 virtual shared_ptr<ForkedProcess> clone() const
3103 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3108 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3109 from_utf8(fname_.absFileName())));
3110 return run(DontWait);
3114 virtual int generateChild();
3116 Buffer const & buffer_;
3121 int AutoSaveBuffer::generateChild()
3123 #if defined(__APPLE__)
3124 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3125 * We should use something else like threads.
3127 * Since I do not know how to determine at run time what is the OS X
3128 * version, I just disable forking altogether for now (JMarc)
3130 pid_t const pid = -1;
3132 // tmp_ret will be located (usually) in /tmp
3133 // will that be a problem?
3134 // Note that this calls ForkedCalls::fork(), so it's
3135 // ok cross-platform.
3136 pid_t const pid = fork();
3137 // If you want to debug the autosave
3138 // you should set pid to -1, and comment out the fork.
3139 if (pid != 0 && pid != -1)
3143 // pid = -1 signifies that lyx was unable
3144 // to fork. But we will do the save
3146 bool failed = false;
3147 FileName const tmp_ret = FileName::tempName("lyxauto");
3148 if (!tmp_ret.empty()) {
3149 buffer_.writeFile(tmp_ret);
3150 // assume successful write of tmp_ret
3151 if (!tmp_ret.moveTo(fname_))
3157 // failed to write/rename tmp_ret so try writing direct
3158 if (!buffer_.writeFile(fname_)) {
3159 // It is dangerous to do this in the child,
3160 // but safe in the parent, so...
3161 if (pid == -1) // emit message signal.
3162 buffer_.message(_("Autosave failed!"));
3166 if (pid == 0) // we are the child so...
3175 FileName Buffer::getAutosaveFileName() const
3177 // if the document is unnamed try to save in the backup dir, else
3178 // in the default document path, and as a last try in the filePath,
3179 // which will most often be the temporary directory
3182 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3183 : lyxrc.backupdir_path;
3184 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3187 string const fname = "#" + d->filename.onlyFileName() + "#";
3188 return makeAbsPath(fname, fpath);
3192 void Buffer::removeAutosaveFile() const
3194 FileName const f = getAutosaveFileName();
3200 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3202 FileName const newauto = getAutosaveFileName();
3204 if (newauto != oldauto && oldauto.exists())
3205 if (!oldauto.moveTo(newauto))
3206 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3210 // Perfect target for a thread...
3211 void Buffer::autoSave() const
3213 if (d->bak_clean || isReadonly()) {
3214 // We don't save now, but we'll try again later
3215 resetAutosaveTimers();
3219 // emit message signal.
3220 message(_("Autosaving current document..."));
3221 AutoSaveBuffer autosave(*this, getAutosaveFileName());
3224 d->bak_clean = true;
3226 resetAutosaveTimers();
3230 string Buffer::bufferFormat() const
3232 string format = params().documentClass().outputFormat();
3233 if (format == "latex") {
3234 if (params().useXetex)
3236 if (params().encoding().package() == Encoding::japanese)
3243 string Buffer::getDefaultOutputFormat() const
3245 if (!params().defaultOutputFormat.empty()
3246 && params().defaultOutputFormat != "default")
3247 return params().defaultOutputFormat;
3248 typedef vector<Format const *> Formats;
3249 Formats formats = exportableFormats(true);
3252 || params().useXetex
3253 || params().encoding().package() == Encoding::japanese) {
3254 if (formats.empty())
3256 // return the first we find
3257 return formats.front()->name();
3259 return lyxrc.default_view_format;
3264 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3265 bool includeall, string & result_file) const
3267 string backend_format;
3268 OutputParams runparams(¶ms().encoding());
3269 runparams.flavor = OutputParams::LATEX;
3270 runparams.linelen = lyxrc.plaintext_linelen;
3271 runparams.includeall = includeall;
3272 vector<string> backs = backends();
3273 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3274 // Get shortest path to format
3275 Graph::EdgePath path;
3276 for (vector<string>::const_iterator it = backs.begin();
3277 it != backs.end(); ++it) {
3278 Graph::EdgePath p = theConverters().getPath(*it, format);
3279 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3280 backend_format = *it;
3285 if (!put_in_tempdir) {
3286 // Only show this alert if this is an export to a non-temporary
3287 // file (not for previewing).
3288 Alert::error(_("Couldn't export file"), bformat(
3289 _("No information for exporting the format %1$s."),
3290 formats.prettyName(format)));
3294 runparams.flavor = theConverters().getFlavor(path);
3297 backend_format = format;
3298 // FIXME: Don't hardcode format names here, but use a flag
3299 if (backend_format == "pdflatex")
3300 runparams.flavor = OutputParams::PDFLATEX;
3303 string filename = latexName(false);
3304 filename = addName(temppath(), filename);
3305 filename = changeExtension(filename,
3306 formats.extension(backend_format));
3309 updateMacroInstances();
3311 // Plain text backend
3312 if (backend_format == "text") {
3313 runparams.flavor = OutputParams::TEXT;
3314 writePlaintextFile(*this, FileName(filename), runparams);
3317 else if (backend_format == "xhtml") {
3318 runparams.flavor = OutputParams::HTML;
3319 switch (params().html_math_output) {
3320 case BufferParams::MathML:
3321 runparams.math_flavor = OutputParams::MathAsMathML;
3323 case BufferParams::HTML:
3324 runparams.math_flavor = OutputParams::MathAsHTML;
3326 case BufferParams::Images:
3327 runparams.math_flavor = OutputParams::MathAsImages;
3329 case BufferParams::LaTeX:
3330 runparams.math_flavor = OutputParams::MathAsLaTeX;
3334 makeLyXHTMLFile(FileName(filename), runparams);
3335 } else if (backend_format == "lyx")
3336 writeFile(FileName(filename));
3338 else if (isDocBook()) {
3339 runparams.nice = !put_in_tempdir;
3340 makeDocBookFile(FileName(filename), runparams);
3343 else if (backend_format == format) {
3344 runparams.nice = true;
3345 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3347 } else if (!lyxrc.tex_allows_spaces
3348 && contains(filePath(), ' ')) {
3349 Alert::error(_("File name error"),
3350 _("The directory path to the document cannot contain spaces."));
3353 runparams.nice = false;
3354 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3358 string const error_type = (format == "program")
3359 ? "Build" : bufferFormat();
3360 ErrorList & error_list = d->errorLists[error_type];
3361 string const ext = formats.extension(format);
3362 FileName const tmp_result_file(changeExtension(filename, ext));
3363 bool const success = theConverters().convert(this, FileName(filename),
3364 tmp_result_file, FileName(absFileName()), backend_format, format,
3367 // Emit the signal to show the error list or copy it back to the
3368 // cloned Buffer so that it cab be emitted afterwards.
3369 if (format != backend_format) {
3370 if (d->cloned_buffer_) {
3371 d->cloned_buffer_->d->errorLists[error_type] =
3372 d->errorLists[error_type];
3375 // also to the children, in case of master-buffer-view
3376 std::vector<Buffer *> clist = getChildren();
3377 for (vector<Buffer *>::const_iterator cit = clist.begin();
3378 cit != clist.end(); ++cit) {
3379 if (d->cloned_buffer_) {
3380 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3381 (*cit)->d->errorLists[error_type];
3383 (*cit)->errors(error_type, true);
3387 if (d->cloned_buffer_) {
3388 // Enable reverse dvi or pdf to work by copying back the texrow
3389 // object to the cloned buffer.
3390 // FIXME: There is a possibility of concurrent access to texrow
3391 // here from the main GUI thread that should be securized.
3392 d->cloned_buffer_->d->texrow = d->texrow;
3393 string const error_type = bufferFormat();
3394 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3400 if (put_in_tempdir) {
3401 result_file = tmp_result_file.absFileName();
3405 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3406 // We need to copy referenced files (e. g. included graphics
3407 // if format == "dvi") to the result dir.
3408 vector<ExportedFile> const files =
3409 runparams.exportdata->externalFiles(format);
3410 string const dest = onlyPath(result_file);
3411 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3412 : force_overwrite == ALL_FILES;
3413 CopyStatus status = use_force ? FORCE : SUCCESS;
3415 vector<ExportedFile>::const_iterator it = files.begin();
3416 vector<ExportedFile>::const_iterator const en = files.end();
3417 for (; it != en && status != CANCEL; ++it) {
3418 string const fmt = formats.getFormatFromFile(it->sourceName);
3419 status = copyFile(fmt, it->sourceName,
3420 makeAbsPath(it->exportName, dest),
3421 it->exportName, status == FORCE);
3424 if (status == CANCEL) {
3425 message(_("Document export cancelled."));
3426 } else if (tmp_result_file.exists()) {
3427 // Finally copy the main file
3428 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3429 : force_overwrite != NO_FILES;
3430 if (status == SUCCESS && use_force)
3432 status = copyFile(format, tmp_result_file,
3433 FileName(result_file), result_file,
3435 message(bformat(_("Document exported as %1$s "
3437 formats.prettyName(format),
3438 makeDisplayPath(result_file)));
3440 // This must be a dummy converter like fax (bug 1888)
3441 message(bformat(_("Document exported as %1$s"),
3442 formats.prettyName(format)));
3449 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3450 bool includeall) const
3453 // (1) export with all included children (omit \includeonly)
3454 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3456 // (2) export with included children only
3457 return doExport(format, put_in_tempdir, false, result_file);
3461 bool Buffer::preview(string const & format, bool includeall) const
3464 // (1) export with all included children (omit \includeonly)
3465 if (includeall && !doExport(format, true, true))
3467 // (2) export with included children only
3468 if (!doExport(format, true, false, result_file))
3470 return formats.view(*this, FileName(result_file), format);
3474 bool Buffer::isExportable(string const & format) const
3476 vector<string> backs = backends();
3477 for (vector<string>::const_iterator it = backs.begin();
3478 it != backs.end(); ++it)
3479 if (theConverters().isReachable(*it, format))
3485 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3487 vector<string> const backs = backends();
3488 vector<Format const *> result =
3489 theConverters().getReachable(backs[0], only_viewable, true);
3490 for (vector<string>::const_iterator it = backs.begin() + 1;
3491 it != backs.end(); ++it) {
3492 vector<Format const *> r =
3493 theConverters().getReachable(*it, only_viewable, false);
3494 result.insert(result.end(), r.begin(), r.end());
3500 vector<string> Buffer::backends() const
3503 v.push_back(bufferFormat());
3504 // FIXME: Don't hardcode format names here, but use a flag
3505 if (v.back() == "latex")
3506 v.push_back("pdflatex");
3507 v.push_back("xhtml");
3508 v.push_back("text");
3514 bool Buffer::readFileHelper(FileName const & s)
3516 // File information about normal file
3518 docstring const file = makeDisplayPath(s.absFileName(), 50);
3519 docstring text = bformat(_("The specified document\n%1$s"
3520 "\ncould not be read."), file);
3521 Alert::error(_("Could not read document"), text);
3525 // Check if emergency save file exists and is newer.
3526 FileName const e(s.absFileName() + ".emergency");
3528 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3529 docstring const file = makeDisplayPath(s.absFileName(), 20);
3530 docstring const text =
3531 bformat(_("An emergency save of the document "
3533 "Recover emergency save?"), file);
3534 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3535 _("&Recover"), _("&Load Original"),
3539 // the file is not saved if we load the emergency file.
3544 if ((res = readFile(e)) == success)
3545 str = _("Document was successfully recovered.");
3547 str = _("Document was NOT successfully recovered.");
3548 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3549 makeDisplayPath(e.absFileName()));
3551 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3552 _("&Remove"), _("&Keep it"))) {
3555 Alert::warning(_("Emergency file deleted"),
3556 _("Do not forget to save your file now!"), true);
3561 if (!Alert::prompt(_("Delete emergency file?"),
3562 _("Remove emergency file now?"), 1, 1,
3563 _("&Remove"), _("&Keep it")))
3571 // Now check if autosave file is newer.
3572 FileName const a(onlyPath(s.absFileName()) + '#' + onlyFileName(s.absFileName()) + '#');
3574 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3575 docstring const file = makeDisplayPath(s.absFileName(), 20);
3576 docstring const text =
3577 bformat(_("The backup of the document "
3578 "%1$s is newer.\n\nLoad the "
3579 "backup instead?"), file);
3580 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3581 _("&Load backup"), _("Load &original"),
3585 // the file is not saved if we load the autosave file.
3589 // Here we delete the autosave
3600 bool Buffer::loadLyXFile(FileName const & s)
3602 // If the file is not readable, we try to
3603 // retrieve the file from version control.
3604 if (!s.isReadableFile()
3605 && !LyXVC::file_not_found_hook(s))
3608 if (s.isReadableFile()){
3609 // InsetInfo needs to know if file is under VCS
3610 lyxvc().file_found_hook(s);
3611 if (readFileHelper(s)) {
3612 d->read_only = !s.isWritable();
3620 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3622 TeXErrors::Errors::const_iterator cit = terr.begin();
3623 TeXErrors::Errors::const_iterator end = terr.end();
3625 for (; cit != end; ++cit) {
3628 int errorRow = cit->error_in_line;
3629 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3635 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3636 } while (found && id_start == id_end && pos_start == pos_end);
3638 errorList.push_back(ErrorItem(cit->error_desc,
3639 cit->error_text, id_start, pos_start, pos_end));
3644 void Buffer::setBuffersForInsets() const
3646 inset().setBuffer(const_cast<Buffer &>(*this));
3650 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3652 // Use the master text class also for child documents
3653 Buffer const * const master = masterBuffer();
3654 DocumentClass const & textclass = master->params().documentClass();
3656 // do this only if we are the top-level Buffer
3657 if (scope != UpdateMaster || master == this)
3658 checkBibInfoCache();
3660 // keep the buffers to be children in this set. If the call from the
3661 // master comes back we can see which of them were actually seen (i.e.
3662 // via an InsetInclude). The remaining ones in the set need still be updated.
3663 static std::set<Buffer const *> bufToUpdate;
3664 if (scope == UpdateMaster) {
3665 // If this is a child document start with the master
3666 if (master != this) {
3667 bufToUpdate.insert(this);
3668 master->updateBuffer(UpdateMaster, utype);
3669 // Do this here in case the master has no gui associated with it. Then,
3670 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3671 if (!master->d->gui_)
3674 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3675 if (bufToUpdate.find(this) == bufToUpdate.end())
3679 // start over the counters in the master
3680 textclass.counters().reset();
3683 // update will be done below for this buffer
3684 bufToUpdate.erase(this);
3686 // update all caches
3687 clearReferenceCache();
3690 Buffer & cbuf = const_cast<Buffer &>(*this);
3692 LASSERT(!text().paragraphs().empty(), /**/);
3695 ParIterator parit = cbuf.par_iterator_begin();
3696 updateBuffer(parit, utype);
3699 // TocBackend update will be done later.
3702 cbuf.tocBackend().update();
3703 if (scope == UpdateMaster)
3704 cbuf.structureChanged();
3708 static depth_type getDepth(DocIterator const & it)
3710 depth_type depth = 0;
3711 for (size_t i = 0 ; i < it.depth() ; ++i)
3712 if (!it[i].inset().inMathed())
3713 depth += it[i].paragraph().getDepth() + 1;
3714 // remove 1 since the outer inset does not count
3718 static depth_type getItemDepth(ParIterator const & it)
3720 Paragraph const & par = *it;
3721 LabelType const labeltype = par.layout().labeltype;
3723 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3726 // this will hold the lowest depth encountered up to now.
3727 depth_type min_depth = getDepth(it);
3728 ParIterator prev_it = it;
3731 --prev_it.top().pit();
3733 // start of nested inset: go to outer par
3735 if (prev_it.empty()) {
3736 // start of document: nothing to do
3741 // We search for the first paragraph with same label
3742 // that is not more deeply nested.
3743 Paragraph & prev_par = *prev_it;
3744 depth_type const prev_depth = getDepth(prev_it);
3745 if (labeltype == prev_par.layout().labeltype) {
3746 if (prev_depth < min_depth)
3747 return prev_par.itemdepth + 1;
3748 if (prev_depth == min_depth)
3749 return prev_par.itemdepth;
3751 min_depth = min(min_depth, prev_depth);
3752 // small optimization: if we are at depth 0, we won't
3753 // find anything else
3754 if (prev_depth == 0)
3760 static bool needEnumCounterReset(ParIterator const & it)
3762 Paragraph const & par = *it;
3763 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3764 depth_type const cur_depth = par.getDepth();
3765 ParIterator prev_it = it;
3766 while (prev_it.pit()) {
3767 --prev_it.top().pit();
3768 Paragraph const & prev_par = *prev_it;
3769 if (prev_par.getDepth() <= cur_depth)
3770 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3772 // start of nested inset: reset
3777 // set the label of a paragraph. This includes the counters.
3778 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3780 BufferParams const & bp = owner_->masterBuffer()->params();
3781 DocumentClass const & textclass = bp.documentClass();
3782 Paragraph & par = it.paragraph();
3783 Layout const & layout = par.layout();
3784 Counters & counters = textclass.counters();
3786 if (par.params().startOfAppendix()) {
3787 // FIXME: only the counter corresponding to toplevel
3788 // sectioning should be reset
3790 counters.appendix(true);
3792 par.params().appendix(counters.appendix());
3794 // Compute the item depth of the paragraph
3795 par.itemdepth = getItemDepth(it);
3797 if (layout.margintype == MARGIN_MANUAL
3798 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3799 if (par.params().labelWidthString().empty())
3800 par.params().labelWidthString(par.expandLabel(layout, bp));
3802 par.params().labelWidthString(docstring());
3805 switch(layout.labeltype) {
3807 if (layout.toclevel <= bp.secnumdepth
3808 && (layout.latextype != LATEX_ENVIRONMENT
3809 || it.text()->isFirstInSequence(it.pit()))) {
3810 counters.step(layout.counter, utype);
3811 par.params().labelString(
3812 par.expandLabel(layout, bp));
3814 par.params().labelString(docstring());
3817 case LABEL_ITEMIZE: {
3818 // At some point of time we should do something more
3819 // clever here, like:
3820 // par.params().labelString(
3821 // bp.user_defined_bullet(par.itemdepth).getText());
3822 // for now, use a simple hardcoded label
3823 docstring itemlabel;
3824 switch (par.itemdepth) {
3826 itemlabel = char_type(0x2022);
3829 itemlabel = char_type(0x2013);
3832 itemlabel = char_type(0x2217);
3835 itemlabel = char_type(0x2219); // or 0x00b7
3838 par.params().labelString(itemlabel);
3842 case LABEL_ENUMERATE: {
3843 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3845 switch (par.itemdepth) {
3854 enumcounter += "iv";
3857 // not a valid enumdepth...
3861 // Maybe we have to reset the enumeration counter.
3862 if (needEnumCounterReset(it))
3863 counters.reset(enumcounter);
3864 counters.step(enumcounter, utype);
3866 string const & lang = par.getParLanguage(bp)->code();
3867 par.params().labelString(counters.theCounter(enumcounter, lang));
3872 case LABEL_SENSITIVE: {
3873 string const & type = counters.current_float();
3874 docstring full_label;
3876 full_label = owner_->B_("Senseless!!! ");
3878 docstring name = owner_->B_(textclass.floats().getType(type).name());
3879 if (counters.hasCounter(from_utf8(type))) {
3880 string const & lang = par.getParLanguage(bp)->code();
3881 counters.step(from_utf8(type), utype);
3882 full_label = bformat(from_ascii("%1$s %2$s:"),
3884 counters.theCounter(from_utf8(type), lang));
3886 full_label = bformat(from_ascii("%1$s #:"), name);
3888 par.params().labelString(full_label);
3892 case LABEL_NO_LABEL:
3893 par.params().labelString(docstring());
3897 case LABEL_TOP_ENVIRONMENT:
3898 case LABEL_CENTERED_TOP_ENVIRONMENT:
3901 par.params().labelString(par.expandLabel(layout, bp));
3907 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
3909 LASSERT(parit.pit() == 0, /**/);
3911 // set the position of the text in the buffer to be able
3912 // to resolve macros in it. This has nothing to do with
3913 // labels, but by putting it here we avoid implementing
3914 // a whole bunch of traversal routines just for this call.
3915 parit.text()->setMacrocontextPosition(parit);
3917 depth_type maxdepth = 0;
3918 pit_type const lastpit = parit.lastpit();
3919 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3920 // reduce depth if necessary
3921 parit->params().depth(min(parit->params().depth(), maxdepth));
3922 maxdepth = parit->getMaxDepthAfter();
3924 if (utype == OutputUpdate) {
3925 // track the active counters
3926 // we have to do this for the master buffer, since the local
3927 // buffer isn't tracking anything.
3928 masterBuffer()->params().documentClass().counters().
3929 setActiveLayout(parit->layout());
3932 // set the counter for this paragraph
3933 d->setLabel(parit, utype);
3936 InsetList::const_iterator iit = parit->insetList().begin();
3937 InsetList::const_iterator end = parit->insetList().end();
3938 for (; iit != end; ++iit) {
3939 parit.pos() = iit->pos;
3940 iit->inset->updateBuffer(parit, utype);
3946 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3947 WordLangTuple & word_lang, docstring_list & suggestions) const
3951 suggestions.clear();
3952 word_lang = WordLangTuple();
3953 // OK, we start from here.
3954 DocIterator const end = doc_iterator_end(this);
3955 for (; from != end; from.forwardPos()) {
3956 // We are only interested in text so remove the math CursorSlice.
3957 while (from.inMathed()) {
3961 // If from is at the end of the document (which is possible
3962 // when leaving the mathed) LyX will crash later.
3966 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3971 // Do not increase progress when from == to, otherwise the word
3972 // count will be wrong.
3982 bool Buffer::reload()
3986 removeAutosaveFile();
3987 // e.g., read-only status could have changed due to version control
3988 d->filename.refresh();
3989 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
3991 bool const success = loadLyXFile(d->filename);
3997 message(bformat(_("Document %1$s reloaded."), disp_fn));
3999 message(bformat(_("Could not reload document %1$s."), disp_fn));
4002 thePreviews().removeLoader(*this);
4003 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
4004 thePreviews().generateBufferPreviews(*this);
4010 // FIXME We could do better here, but it is complicated. What would be
4011 // nice is to offer either (a) to save the child buffer to an appropriate
4012 // location, so that it would "move with the master", or else (b) to update
4013 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4014 // complicated, because the code for this lives in GuiView.
4015 void Buffer::checkChildBuffers()
4017 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4018 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4019 for (; it != en; ++it) {
4020 DocIterator dit = it->second;
4021 Buffer * cbuf = const_cast<Buffer *>(it->first);
4022 if (!cbuf || !theBufferList().isLoaded(cbuf))
4024 Inset * inset = dit.nextInset();
4025 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4026 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4027 docstring const & incfile = inset_inc->getParam("filename");
4028 string oldloc = cbuf->absFileName();
4029 string newloc = makeAbsPath(to_utf8(incfile),
4030 onlyPath(absFileName())).absFileName();
4031 if (oldloc == newloc)
4033 // the location of the child file is incorrect.
4034 Alert::warning(_("Included File Invalid"),
4035 bformat(_("Saving this document to a new location has made the file:\n"
4037 "inaccessible. You will need to update the included filename."),
4038 from_utf8(oldloc)));
4040 inset_inc->setChildBuffer(0);
4042 // invalidate cache of children
4043 d->children_positions.clear();
4044 d->position_to_children.clear();