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);
169 void setLabel(ParIterator & it, UpdateType utype) const;
171 void collectRelatives(BufferSet & bufs) const;
173 /** If we have branches that use the file suffix
174 feature, return the file name with suffix appended.
176 support::FileName exportFileName() const;
183 mutable TexRow texrow;
185 /// need to regenerate .tex?
189 mutable bool lyx_clean;
191 /// is autosave needed?
192 mutable bool bak_clean;
194 /// is this a unnamed file (New...)?
200 /// name of the file the buffer is associated with.
203 /** Set to true only when the file is fully loaded.
204 * Used to prevent the premature generation of previews
205 * and by the citation inset.
207 bool file_fully_loaded;
210 mutable TocBackend toc_backend;
213 typedef pair<DocIterator, MacroData> ScopeMacro;
214 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
215 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
216 /// map from the macro name to the position map,
217 /// which maps the macro definition position to the scope and the MacroData.
218 NamePositionScopeMacroMap macros;
219 /// This seem to change the way Buffer::getMacro() works
220 mutable bool macro_lock;
222 /// positions of child buffers in the buffer
223 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
224 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
225 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
226 /// position of children buffers in this buffer
227 BufferPositionMap children_positions;
228 /// map from children inclusion positions to their scope and their buffer
229 PositionScopeBufferMap position_to_children;
231 /// Container for all sort of Buffer dependant errors.
232 map<string, ErrorList> errorLists;
234 /// timestamp and checksum used to test if the file has been externally
235 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
237 unsigned long checksum_;
240 frontend::WorkAreaManager * wa_;
242 frontend::GuiBufferDelegate * gui_;
247 /// A cache for the bibfiles (including bibfiles of loaded child
248 /// documents), needed for appropriate update of natbib labels.
249 mutable support::FileNameList bibfiles_cache_;
251 // FIXME The caching mechanism could be improved. At present, we have a
252 // cache for each Buffer, that caches all the bibliography info for that
253 // Buffer. A more efficient solution would be to have a global cache per
254 // file, and then to construct the Buffer's bibinfo from that.
255 /// A cache for bibliography info
256 mutable BiblioInfo bibinfo_;
257 /// whether the bibinfo cache is valid
258 mutable bool bibinfo_cache_valid_;
259 /// whether the bibfile cache is valid
260 mutable bool bibfile_cache_valid_;
261 /// Cache of timestamps of .bib files
262 map<FileName, time_t> bibfile_status_;
264 mutable RefCache ref_cache_;
266 /// our Text that should be wrapped in an InsetText
269 /// This is here to force the test to be done whenever parent_buffer
271 Buffer const * parent() const {
272 // if parent_buffer is not loaded, then it has been unloaded,
273 // which means that parent_buffer is an invalid pointer. So we
274 // set it to null in that case.
275 // however, the BufferList doesn't know about cloned buffers, so
276 // they will always be regarded as unloaded. in that case, we hope
278 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
280 return parent_buffer;
284 void setParent(Buffer const * pb) {
285 if (parent_buffer == pb)
288 if (!cloned_buffer_ && parent_buffer && pb)
289 LYXERR0("Warning: a buffer should not have two parents!");
291 if (!cloned_buffer_ && parent_buffer) {
292 parent_buffer->invalidateBibfileCache();
293 parent_buffer->invalidateBibinfoCache();
297 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
298 /// This one is useful for preview detached in a thread.
299 Buffer const * cloned_buffer_;
300 /// are we in the process of exporting this buffer?
301 mutable bool doing_export;
304 /// So we can force access via the accessors.
305 mutable Buffer const * parent_buffer;
310 /// Creates the per buffer temporary directory
311 static FileName createBufferTmpDir()
314 // We are in our own directory. Why bother to mangle name?
315 // In fact I wrote this code to circumvent a problematic behaviour
316 // (bug?) of EMX mkstemp().
317 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
318 convert<string>(count++));
320 if (!tmpfl.createDirectory(0777)) {
321 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
322 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
323 from_utf8(tmpfl.absFileName())));
329 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
330 Buffer const * cloned_buffer)
331 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
332 read_only(readonly_), filename(file), file_fully_loaded(false),
333 toc_backend(owner), macro_lock(false), timestamp_(0),
334 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
335 bibfile_cache_valid_(false), cloned_buffer_(cloned_buffer),
336 doing_export(false), parent_buffer(0)
338 if (!cloned_buffer_) {
339 temppath = createBufferTmpDir();
340 lyxvc.setBuffer(owner_);
342 wa_ = new frontend::WorkAreaManager;
345 temppath = cloned_buffer_->d->temppath;
346 file_fully_loaded = true;
347 params = cloned_buffer_->d->params;
348 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
349 bibinfo_ = cloned_buffer_->d->bibinfo_;
350 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
351 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
352 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
356 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
357 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
359 LYXERR(Debug::INFO, "Buffer::Buffer()");
361 d->inset = new InsetText(*cloned_buffer->d->inset);
362 d->inset->setBuffer(*this);
363 // FIXME: optimize this loop somewhat, maybe by creating a new
364 // general recursive Inset::setId().
365 DocIterator it = doc_iterator_begin(this);
366 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
367 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
368 it.paragraph().setId(cloned_it.paragraph().id());
370 d->inset = new InsetText(this);
371 d->inset->setAutoBreakRows(true);
372 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
378 LYXERR(Debug::INFO, "Buffer::~Buffer()");
379 // here the buffer should take care that it is
380 // saved properly, before it goes into the void.
382 // GuiView already destroyed
386 // No need to do additional cleanups for internal buffer.
391 // loop over children
392 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
393 Impl::BufferPositionMap::iterator end = d->children_positions.end();
394 for (; it != end; ++it) {
395 Buffer * child = const_cast<Buffer *>(it->first);
396 if (d->cloned_buffer_)
398 // The child buffer might have been closed already.
399 else if (theBufferList().isLoaded(child))
400 theBufferList().releaseChild(this, child);
404 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
405 msg += emergencyWrite();
406 Alert::warning(_("Attempting to close changed document!"), msg);
409 // clear references to children in macro tables
410 d->children_positions.clear();
411 d->position_to_children.clear();
413 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
414 Alert::warning(_("Could not remove temporary directory"),
415 bformat(_("Could not remove the temporary directory %1$s"),
416 from_utf8(d->temppath.absFileName())));
419 // Remove any previewed LaTeX snippets associated with this buffer.
421 thePreviews().removeLoader(*this);
427 Buffer * Buffer::clone() const
429 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
430 buffer_clone->d->macro_lock = true;
431 buffer_clone->d->children_positions.clear();
432 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
433 // math macro caches need to be rethought and simplified.
434 // I am not sure wether we should handle Buffer cloning here or in BufferList.
435 // Right now BufferList knows nothing about buffer clones.
436 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
437 Impl::BufferPositionMap::iterator end = d->children_positions.end();
438 for (; it != end; ++it) {
439 DocIterator dit = it->second.clone(buffer_clone);
440 dit.setBuffer(buffer_clone);
441 Buffer * child = const_cast<Buffer *>(it->first);
442 Buffer * child_clone = child->clone();
443 Inset * inset = dit.nextInset();
444 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
445 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
446 inset_inc->setChildBuffer(child_clone);
447 child_clone->d->setParent(buffer_clone);
448 buffer_clone->setChild(dit, child_clone);
450 buffer_clone->d->macro_lock = false;
455 bool Buffer::isClone() const
457 return d->cloned_buffer_;
461 void Buffer::changed(bool update_metrics) const
464 d->wa_->redrawAll(update_metrics);
468 frontend::WorkAreaManager & Buffer::workAreaManager() const
470 LASSERT(d->wa_, /**/);
475 Text & Buffer::text() const
477 return d->inset->text();
481 Inset & Buffer::inset() const
487 BufferParams & Buffer::params()
493 BufferParams const & Buffer::params() const
499 ParagraphList & Buffer::paragraphs()
501 return text().paragraphs();
505 ParagraphList const & Buffer::paragraphs() const
507 return text().paragraphs();
511 LyXVC & Buffer::lyxvc()
517 LyXVC const & Buffer::lyxvc() const
523 string const Buffer::temppath() const
525 return d->temppath.absFileName();
529 TexRow & Buffer::texrow()
535 TexRow const & Buffer::texrow() const
541 TocBackend & Buffer::tocBackend() const
543 return d->toc_backend;
547 Undo & Buffer::undo()
553 void Buffer::setChild(DocIterator const & dit, Buffer * child)
555 d->children_positions[child] = dit;
559 string Buffer::latexName(bool const no_path) const
561 FileName latex_name =
562 makeLatexName(d->exportFileName());
563 return no_path ? latex_name.onlyFileName()
564 : latex_name.absFileName();
568 FileName Buffer::Impl::exportFileName() const
570 docstring const branch_suffix =
571 params.branchlist().getFileNameSuffix();
572 if (branch_suffix.empty())
575 string const name = filename.onlyFileNameWithoutExt()
576 + to_utf8(branch_suffix);
577 FileName res(filename.onlyPath().absFileName() + "/" + name);
578 res.changeExtension(filename.extension());
584 string Buffer::logName(LogType * type) const
586 string const filename = latexName(false);
588 if (filename.empty()) {
594 string const path = temppath();
596 FileName const fname(addName(temppath(),
597 onlyFileName(changeExtension(filename,
600 // FIXME: how do we know this is the name of the build log?
601 FileName const bname(
602 addName(path, onlyFileName(
603 changeExtension(filename,
604 formats.extension(bufferFormat()) + ".out"))));
606 // Also consider the master buffer log file
607 FileName masterfname = fname;
609 if (masterBuffer() != this) {
610 string const mlogfile = masterBuffer()->logName(&mtype);
611 masterfname = FileName(mlogfile);
614 // If no Latex log or Build log is newer, show Build log
615 if (bname.exists() &&
616 ((!fname.exists() && !masterfname.exists())
617 || (fname.lastModified() < bname.lastModified()
618 && masterfname.lastModified() < bname.lastModified()))) {
619 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
622 return bname.absFileName();
623 // If we have a newer master file log or only a master log, show this
624 } else if (fname != masterfname
625 && (!fname.exists() && (masterfname.exists()
626 || fname.lastModified() < masterfname.lastModified()))) {
627 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
630 return masterfname.absFileName();
632 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
635 return fname.absFileName();
639 void Buffer::setReadonly(bool const flag)
641 if (d->read_only != flag) {
648 void Buffer::setFileName(string const & newfile)
650 d->filename = makeAbsPath(newfile);
651 setReadonly(d->filename.isReadOnly());
656 int Buffer::readHeader(Lexer & lex)
658 int unknown_tokens = 0;
660 int begin_header_line = -1;
662 // Initialize parameters that may be/go lacking in header:
663 params().branchlist().clear();
664 params().preamble.erase();
665 params().options.erase();
666 params().master.erase();
667 params().float_placement.erase();
668 params().paperwidth.erase();
669 params().paperheight.erase();
670 params().leftmargin.erase();
671 params().rightmargin.erase();
672 params().topmargin.erase();
673 params().bottommargin.erase();
674 params().headheight.erase();
675 params().headsep.erase();
676 params().footskip.erase();
677 params().columnsep.erase();
678 params().fontsCJK.erase();
679 params().listings_params.clear();
680 params().clearLayoutModules();
681 params().clearRemovedModules();
682 params().clearIncludedChildren();
683 params().pdfoptions().clear();
684 params().indiceslist().clear();
685 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
686 params().isbackgroundcolor = false;
687 params().fontcolor = lyx::rgbFromHexName("#000000");
688 params().isfontcolor = false;
689 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
690 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
691 params().html_latex_start.clear();
692 params().html_latex_end.clear();
693 params().html_math_img_scale = 1.0;
694 params().output_sync_macro.erase();
696 for (int i = 0; i < 4; ++i) {
697 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
698 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
701 ErrorList & errorList = d->errorLists["Parse"];
710 if (token == "\\end_header")
714 if (token == "\\begin_header") {
715 begin_header_line = line;
719 LYXERR(Debug::PARSER, "Handling document header token: `"
722 string unknown = params().readToken(lex, token, d->filename.onlyPath());
723 if (!unknown.empty()) {
724 if (unknown[0] != '\\' && token == "\\textclass") {
725 Alert::warning(_("Unknown document class"),
726 bformat(_("Using the default document class, because the "
727 "class %1$s is unknown."), from_utf8(unknown)));
730 docstring const s = bformat(_("Unknown token: "
734 errorList.push_back(ErrorItem(_("Document header error"),
739 if (begin_header_line) {
740 docstring const s = _("\\begin_header is missing");
741 errorList.push_back(ErrorItem(_("Document header error"),
745 params().makeDocumentClass();
747 return unknown_tokens;
752 // changed to be public and have one parameter
753 // Returns true if "\end_document" is not read (Asger)
754 bool Buffer::readDocument(Lexer & lex)
756 ErrorList & errorList = d->errorLists["Parse"];
759 if (!lex.checkFor("\\begin_document")) {
760 docstring const s = _("\\begin_document is missing");
761 errorList.push_back(ErrorItem(_("Document header error"),
765 // we are reading in a brand new document
766 LASSERT(paragraphs().empty(), /**/);
770 if (params().outputChanges) {
771 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
772 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
773 LaTeXFeatures::isAvailable("xcolor");
775 if (!dvipost && !xcolorulem) {
776 Alert::warning(_("Changes not shown in LaTeX output"),
777 _("Changes will not be highlighted in LaTeX output, "
778 "because neither dvipost nor xcolor/ulem are installed.\n"
779 "Please install these packages or redefine "
780 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
781 } else if (!xcolorulem) {
782 Alert::warning(_("Changes not shown in LaTeX output"),
783 _("Changes will not be highlighted in LaTeX output "
784 "when using pdflatex, because xcolor and ulem are not installed.\n"
785 "Please install both packages or redefine "
786 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
790 if (!params().master.empty()) {
791 FileName const master_file = makeAbsPath(params().master,
792 onlyPath(absFileName()));
793 if (isLyXFileName(master_file.absFileName())) {
795 checkAndLoadLyXFile(master_file, true);
797 // necessary e.g. after a reload
798 // to re-register the child (bug 5873)
799 // FIXME: clean up updateMacros (here, only
800 // child registering is needed).
801 master->updateMacros();
802 // set master as master buffer, but only
803 // if we are a real child
804 if (master->isChild(this))
806 // if the master is not fully loaded
807 // it is probably just loading this
808 // child. No warning needed then.
809 else if (master->isFullyLoaded())
810 LYXERR0("The master '"
812 << "' assigned to this document ("
814 << ") does not include "
815 "this document. Ignoring the master assignment.");
820 // assure we have a default index
821 params().indiceslist().addDefault(B_("Index"));
824 bool const res = text().read(lex, errorList, d->inset);
828 updateMacroInstances();
833 bool Buffer::readString(string const & s)
835 params().compressed = false;
837 // remove dummy empty par
838 paragraphs().clear();
842 FileName const name = FileName::tempName("Buffer_readString");
843 switch (readFile(lex, name, true)) {
847 // We need to call lyx2lyx, so write the input to a file
848 ofstream os(name.toFilesystemEncoding().c_str());
851 return readFile(name);
861 bool Buffer::readFile(FileName const & filename)
863 FileName fname(filename);
865 params().compressed = fname.isZippedFile();
867 // remove dummy empty par
868 paragraphs().clear();
871 if (readFile(lex, fname) != success)
878 bool Buffer::isFullyLoaded() const
880 return d->file_fully_loaded;
884 void Buffer::setFullyLoaded(bool value)
886 d->file_fully_loaded = value;
890 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
893 LASSERT(!filename.empty(), /**/);
895 // the first (non-comment) token _must_ be...
896 if (!lex.checkFor("\\lyxformat")) {
897 Alert::error(_("Document format failure"),
898 bformat(_("%1$s is not a readable LyX document."),
899 from_utf8(filename.absFileName())));
905 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
906 // if present remove ".," from string.
907 size_t dot = tmp_format.find_first_of(".,");
908 //lyxerr << " dot found at " << dot << endl;
909 if (dot != string::npos)
910 tmp_format.erase(dot, 1);
911 int const file_format = convert<int>(tmp_format);
912 //lyxerr << "format: " << file_format << endl;
914 // save timestamp and checksum of the original disk file, making sure
915 // to not overwrite them with those of the file created in the tempdir
916 // when it has to be converted to the current format.
918 // Save the timestamp and checksum of disk file. If filename is an
919 // emergency file, save the timestamp and checksum of the original lyx file
920 // because isExternallyModified will check for this file. (BUG4193)
921 string diskfile = filename.absFileName();
922 if (suffixIs(diskfile, ".emergency"))
923 diskfile = diskfile.substr(0, diskfile.size() - 10);
924 saveCheckSum(FileName(diskfile));
927 if (file_format != LYX_FORMAT) {
930 // lyx2lyx would fail
933 FileName const tmpfile = FileName::tempName("Buffer_readFile");
934 if (tmpfile.empty()) {
935 Alert::error(_("Conversion failed"),
936 bformat(_("%1$s is from a different"
937 " version of LyX, but a temporary"
938 " file for converting it could"
940 from_utf8(filename.absFileName())));
943 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
944 if (lyx2lyx.empty()) {
945 Alert::error(_("Conversion script not found"),
946 bformat(_("%1$s is from a different"
947 " version of LyX, but the"
948 " conversion script lyx2lyx"
949 " could not be found."),
950 from_utf8(filename.absFileName())));
953 ostringstream command;
954 command << os::python()
955 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
956 << " -t " << convert<string>(LYX_FORMAT)
957 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
958 << ' ' << quoteName(filename.toSafeFilesystemEncoding());
959 string const command_str = command.str();
961 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
963 cmd_ret const ret = runCommand(command_str);
964 if (ret.first != 0) {
965 if (file_format < LYX_FORMAT)
966 Alert::error(_("Conversion script failed"),
967 bformat(_("%1$s is from an older version"
968 " of LyX, but the lyx2lyx script"
969 " failed to convert it."),
970 from_utf8(filename.absFileName())));
972 Alert::error(_("Conversion script failed"),
973 bformat(_("%1$s is from a newer version"
974 " of LyX and cannot be converted by the"
976 from_utf8(filename.absFileName())));
979 bool const ret = readFile(tmpfile);
980 // Do stuff with tmpfile name and buffer name here.
981 return ret ? success : failure;
986 if (readDocument(lex)) {
987 Alert::error(_("Document format failure"),
988 bformat(_("%1$s ended unexpectedly, which means"
989 " that it is probably corrupted."),
990 from_utf8(filename.absFileName())));
994 d->file_fully_loaded = true;
999 // Should probably be moved to somewhere else: BufferView? GuiView?
1000 bool Buffer::save() const
1002 // ask if the disk file has been externally modified (use checksum method)
1003 if (fileName().exists() && isExternallyModified(checksum_method)) {
1004 docstring const file = makeDisplayPath(absFileName(), 20);
1005 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
1006 "you want to overwrite this file?"), file);
1007 int const ret = Alert::prompt(_("Overwrite modified file?"),
1008 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1013 // We don't need autosaves in the immediate future. (Asger)
1014 resetAutosaveTimers();
1016 FileName backupName;
1017 bool madeBackup = false;
1019 // make a backup if the file already exists
1020 if (lyxrc.make_backup && fileName().exists()) {
1021 backupName = FileName(absFileName() + '~');
1022 if (!lyxrc.backupdir_path.empty()) {
1023 string const mangledName =
1024 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1025 backupName = FileName(addName(lyxrc.backupdir_path,
1028 // do not copy because of #6587
1029 if (fileName().moveTo(backupName)) {
1032 Alert::error(_("Backup failure"),
1033 bformat(_("Cannot create backup file %1$s.\n"
1034 "Please check whether the directory exists and is writeable."),
1035 from_utf8(backupName.absFileName())));
1036 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1040 if (writeFile(d->filename)) {
1044 // Saving failed, so backup is not backup
1046 backupName.moveTo(d->filename);
1052 bool Buffer::writeFile(FileName const & fname) const
1054 if (d->read_only && fname == d->filename)
1057 bool retval = false;
1059 docstring const str = bformat(_("Saving document %1$s..."),
1060 makeDisplayPath(fname.absFileName()));
1063 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1065 if (params().compressed) {
1066 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1067 retval = ofs && write(ofs);
1069 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1070 retval = ofs && write(ofs);
1074 message(str + _(" could not write file!"));
1079 // removeAutosaveFile();
1081 saveCheckSum(d->filename);
1082 message(str + _(" done."));
1088 docstring Buffer::emergencyWrite()
1090 // No need to save if the buffer has not changed.
1094 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1096 docstring user_message = bformat(
1097 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1099 // We try to save three places:
1100 // 1) Same place as document. Unless it is an unnamed doc.
1102 string s = absFileName();
1105 if (writeFile(FileName(s))) {
1107 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1108 return user_message;
1110 user_message += _(" Save failed! Trying again...\n");
1114 // 2) In HOME directory.
1115 string s = addName(package().home_dir().absFileName(), absFileName());
1117 lyxerr << ' ' << s << endl;
1118 if (writeFile(FileName(s))) {
1120 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1121 return user_message;
1124 user_message += _(" Save failed! Trying yet again...\n");
1126 // 3) In "/tmp" directory.
1127 // MakeAbsPath to prepend the current
1128 // drive letter on OS/2
1129 s = addName(package().temp_dir().absFileName(), absFileName());
1131 lyxerr << ' ' << s << endl;
1132 if (writeFile(FileName(s))) {
1134 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1135 return user_message;
1138 user_message += _(" Save failed! Bummer. Document is lost.");
1141 return user_message;
1145 bool Buffer::write(ostream & ofs) const
1148 // Use the standard "C" locale for file output.
1149 ofs.imbue(locale::classic());
1152 // The top of the file should not be written by params().
1154 // write out a comment in the top of the file
1155 ofs << "#LyX " << lyx_version
1156 << " created this file. For more info see http://www.lyx.org/\n"
1157 << "\\lyxformat " << LYX_FORMAT << "\n"
1158 << "\\begin_document\n";
1160 /// For each author, set 'used' to true if there is a change
1161 /// by this author in the document; otherwise set it to 'false'.
1162 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1163 AuthorList::Authors::const_iterator a_end = params().authors().end();
1164 for (; a_it != a_end; ++a_it)
1165 a_it->setUsed(false);
1167 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1168 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1169 for ( ; it != end; ++it)
1170 it->checkAuthors(params().authors());
1172 // now write out the buffer parameters.
1173 ofs << "\\begin_header\n";
1174 params().writeFile(ofs);
1175 ofs << "\\end_header\n";
1178 ofs << "\n\\begin_body\n";
1180 ofs << "\n\\end_body\n";
1182 // Write marker that shows file is complete
1183 ofs << "\\end_document" << endl;
1185 // Shouldn't really be needed....
1188 // how to check if close went ok?
1189 // Following is an attempt... (BE 20001011)
1191 // good() returns false if any error occured, including some
1192 // formatting error.
1193 // bad() returns true if something bad happened in the buffer,
1194 // which should include file system full errors.
1199 lyxerr << "File was not closed properly." << endl;
1206 bool Buffer::makeLaTeXFile(FileName const & fname,
1207 string const & original_path,
1208 OutputParams const & runparams_in,
1209 bool output_preamble, bool output_body) const
1211 OutputParams runparams = runparams_in;
1212 if (params().useXetex)
1213 runparams.flavor = OutputParams::XETEX;
1215 string const encoding = runparams.encoding->iconvName();
1216 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1219 try { ofs.reset(encoding); }
1220 catch (iconv_codecvt_facet_exception & e) {
1221 lyxerr << "Caught iconv exception: " << e.what() << endl;
1222 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1223 "verify that the support software for your encoding (%1$s) is "
1224 "properly installed"), from_ascii(encoding)));
1227 if (!openFileWrite(ofs, fname))
1230 //TexStream ts(ofs.rdbuf(), &texrow());
1231 ErrorList & errorList = d->errorLists["Export"];
1233 bool failed_export = false;
1236 writeLaTeXSource(ofs, original_path,
1237 runparams, output_preamble, output_body);
1239 catch (EncodingException & e) {
1240 odocstringstream ods;
1241 ods.put(e.failed_char);
1243 oss << "0x" << hex << e.failed_char << dec;
1244 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1245 " (code point %2$s)"),
1246 ods.str(), from_utf8(oss.str()));
1247 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1248 "representable in the chosen encoding.\n"
1249 "Changing the document encoding to utf8 could help."),
1250 e.par_id, e.pos, e.pos + 1));
1251 failed_export = true;
1253 catch (iconv_codecvt_facet_exception & e) {
1254 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1255 _(e.what()), -1, 0, 0));
1256 failed_export = true;
1258 catch (exception const & e) {
1259 errorList.push_back(ErrorItem(_("conversion failed"),
1260 _(e.what()), -1, 0, 0));
1261 failed_export = true;
1264 lyxerr << "Caught some really weird exception..." << endl;
1270 failed_export = true;
1271 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1275 return !failed_export;
1279 void Buffer::writeLaTeXSource(odocstream & os,
1280 string const & original_path,
1281 OutputParams const & runparams_in,
1282 bool const output_preamble, bool const output_body) const
1284 // The child documents, if any, shall be already loaded at this point.
1286 OutputParams runparams = runparams_in;
1288 // Classify the unicode characters appearing in math insets
1289 Encodings::initUnicodeMath(*this);
1291 // validate the buffer.
1292 LYXERR(Debug::LATEX, " Validating buffer...");
1293 LaTeXFeatures features(*this, params(), runparams);
1295 LYXERR(Debug::LATEX, " Buffer validation done.");
1297 // The starting paragraph of the coming rows is the
1298 // first paragraph of the document. (Asger)
1299 if (output_preamble && runparams.nice) {
1300 os << "%% LyX " << lyx_version << " created this file. "
1301 "For more info, see http://www.lyx.org/.\n"
1302 "%% Do not edit unless you really know what "
1304 d->texrow.newline();
1305 d->texrow.newline();
1307 LYXERR(Debug::INFO, "lyx document header finished");
1309 // Don't move this behind the parent_buffer=0 code below,
1310 // because then the macros will not get the right "redefinition"
1311 // flag as they don't see the parent macros which are output before.
1314 // fold macros if possible, still with parent buffer as the
1315 // macros will be put in the prefix anyway.
1316 updateMacroInstances();
1318 // There are a few differences between nice LaTeX and usual files:
1319 // usual is \batchmode and has a
1320 // special input@path to allow the including of figures
1321 // with either \input or \includegraphics (what figinsets do).
1322 // input@path is set when the actual parameter
1323 // original_path is set. This is done for usual tex-file, but not
1324 // for nice-latex-file. (Matthias 250696)
1325 // Note that input@path is only needed for something the user does
1326 // in the preamble, included .tex files or ERT, files included by
1327 // LyX work without it.
1328 if (output_preamble) {
1329 if (!runparams.nice) {
1330 // code for usual, NOT nice-latex-file
1331 os << "\\batchmode\n"; // changed
1332 // from \nonstopmode
1333 d->texrow.newline();
1335 if (!original_path.empty()) {
1337 // We don't know the encoding of inputpath
1338 docstring const inputpath = from_utf8(support::latex_path(original_path));
1339 docstring uncodable_glyphs;
1340 Encoding const * const enc = runparams.encoding;
1342 for (size_t n = 0; n < inputpath.size(); ++n) {
1343 docstring const glyph =
1344 docstring(1, inputpath[n]);
1345 if (enc->latexChar(inputpath[n], true) != glyph) {
1346 LYXERR0("Uncodable character '"
1348 << "' in input path!");
1349 uncodable_glyphs += glyph;
1354 // warn user if we found uncodable glyphs.
1355 if (!uncodable_glyphs.empty()) {
1356 frontend::Alert::warning(_("Uncodable character in file path"),
1357 support::bformat(_("The path of your document\n"
1359 "contains glyphs that are unknown in the\n"
1360 "current document encoding (namely %2$s).\n"
1361 "This will likely result in incomplete output.\n\n"
1362 "Choose an appropriate document encoding (such as utf8)\n"
1363 "or change the file path name."), inputpath, uncodable_glyphs));
1365 os << "\\makeatletter\n"
1366 << "\\def\\input@path{{"
1367 << inputpath << "/}}\n"
1368 << "\\makeatother\n";
1369 d->texrow.newline();
1370 d->texrow.newline();
1371 d->texrow.newline();
1375 // get parent macros (if this buffer has a parent) which will be
1376 // written at the document begin further down.
1377 MacroSet parentMacros;
1378 listParentMacros(parentMacros, features);
1380 // Write the preamble
1381 runparams.use_babel = params().writeLaTeX(os, features,
1383 d->filename.onlyPath());
1385 runparams.use_japanese = features.isRequired("japanese");
1391 os << "\\begin{document}\n";
1392 d->texrow.newline();
1394 // output the parent macros
1395 MacroSet::iterator it = parentMacros.begin();
1396 MacroSet::iterator end = parentMacros.end();
1397 for (; it != end; ++it) {
1398 int num_lines = (*it)->write(os, true);
1399 d->texrow.newlines(num_lines);
1402 } // output_preamble
1404 d->texrow.start(paragraphs().begin()->id(), 0);
1406 LYXERR(Debug::INFO, "preamble finished, now the body.");
1408 // if we are doing a real file with body, even if this is the
1409 // child of some other buffer, let's cut the link here.
1410 // This happens for example if only a child document is printed.
1411 Buffer const * save_parent = 0;
1412 if (output_preamble) {
1413 save_parent = d->parent();
1418 latexParagraphs(*this, text(), os, d->texrow, runparams);
1420 // Restore the parenthood if needed
1421 if (output_preamble)
1422 d->setParent(save_parent);
1424 // add this just in case after all the paragraphs
1426 d->texrow.newline();
1428 if (output_preamble) {
1429 os << "\\end{document}\n";
1430 d->texrow.newline();
1431 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1433 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1435 runparams_in.encoding = runparams.encoding;
1437 // Just to be sure. (Asger)
1438 d->texrow.newline();
1440 //for (int i = 0; i<d->texrow.rows(); i++) {
1442 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1443 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1446 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1447 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1451 bool Buffer::isLatex() const
1453 return params().documentClass().outputType() == LATEX;
1457 bool Buffer::isLiterate() const
1459 return params().documentClass().outputType() == LITERATE;
1463 bool Buffer::isDocBook() const
1465 return params().documentClass().outputType() == DOCBOOK;
1469 void Buffer::makeDocBookFile(FileName const & fname,
1470 OutputParams const & runparams,
1471 bool const body_only) const
1473 LYXERR(Debug::LATEX, "makeDocBookFile...");
1476 if (!openFileWrite(ofs, fname))
1479 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1483 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1487 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1488 OutputParams const & runparams,
1489 bool const only_body) const
1491 LaTeXFeatures features(*this, params(), runparams);
1496 DocumentClass const & tclass = params().documentClass();
1497 string const top_element = tclass.latexname();
1500 if (runparams.flavor == OutputParams::XML)
1501 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1504 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1507 if (! tclass.class_header().empty())
1508 os << from_ascii(tclass.class_header());
1509 else if (runparams.flavor == OutputParams::XML)
1510 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1511 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1513 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1515 docstring preamble = from_utf8(params().preamble);
1516 if (runparams.flavor != OutputParams::XML ) {
1517 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1518 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1519 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1520 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1523 string const name = runparams.nice
1524 ? changeExtension(absFileName(), ".sgml") : fname;
1525 preamble += features.getIncludedFiles(name);
1526 preamble += features.getLyXSGMLEntities();
1528 if (!preamble.empty()) {
1529 os << "\n [ " << preamble << " ]";
1534 string top = top_element;
1536 if (runparams.flavor == OutputParams::XML)
1537 top += params().language->code();
1539 top += params().language->code().substr(0, 2);
1542 if (!params().options.empty()) {
1544 top += params().options;
1547 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1548 << " file was created by LyX " << lyx_version
1549 << "\n See http://www.lyx.org/ for more information -->\n";
1551 params().documentClass().counters().reset();
1555 sgml::openTag(os, top);
1557 docbookParagraphs(text(), *this, os, runparams);
1558 sgml::closeTag(os, top_element);
1562 void Buffer::makeLyXHTMLFile(FileName const & fname,
1563 OutputParams const & runparams,
1564 bool const body_only) const
1566 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1569 if (!openFileWrite(ofs, fname))
1572 writeLyXHTMLSource(ofs, runparams, body_only);
1576 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1580 void Buffer::writeLyXHTMLSource(odocstream & os,
1581 OutputParams const & runparams,
1582 bool const only_body) const
1584 LaTeXFeatures features(*this, params(), runparams);
1586 updateBuffer(UpdateMaster, OutputUpdate);
1587 d->bibinfo_.makeCitationLabels(*this);
1589 updateMacroInstances();
1592 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1593 << "<!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"
1594 // FIXME Language should be set properly.
1595 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1597 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1598 // FIXME Presumably need to set this right
1599 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1601 docstring const & doctitle = features.htmlTitle();
1603 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1606 os << "\n<!-- Text Class Preamble -->\n"
1607 << features.getTClassHTMLPreamble()
1608 << "\n<!-- Premable Snippets -->\n"
1609 << from_utf8(features.getPreambleSnippets());
1611 os << "\n<!-- Layout-provided Styles -->\n";
1612 docstring const styleinfo = features.getTClassHTMLStyles();
1613 if (!styleinfo.empty()) {
1614 os << "<style type='text/css'>\n"
1618 os << "</head>\n<body>\n";
1622 params().documentClass().counters().reset();
1623 xhtmlParagraphs(text(), *this, xs, runparams);
1625 os << "</body>\n</html>\n";
1629 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1630 // Other flags: -wall -v0 -x
1631 int Buffer::runChktex()
1635 // get LaTeX-Filename
1636 FileName const path(temppath());
1637 string const name = addName(path.absFileName(), latexName());
1638 string const org_path = filePath();
1640 PathChanger p(path); // path to LaTeX file
1641 message(_("Running chktex..."));
1643 // Generate the LaTeX file if neccessary
1644 OutputParams runparams(¶ms().encoding());
1645 runparams.flavor = OutputParams::LATEX;
1646 runparams.nice = false;
1647 runparams.linelen = lyxrc.plaintext_linelen;
1648 makeLaTeXFile(FileName(name), org_path, runparams);
1651 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1652 int const res = chktex.run(terr); // run chktex
1655 Alert::error(_("chktex failure"),
1656 _("Could not run chktex successfully."));
1657 } else if (res > 0) {
1658 ErrorList & errlist = d->errorLists["ChkTeX"];
1660 bufferErrors(terr, errlist);
1671 void Buffer::validate(LaTeXFeatures & features) const
1673 params().validate(features);
1677 for_each(paragraphs().begin(), paragraphs().end(),
1678 bind(&Paragraph::validate, _1, ref(features)));
1680 if (lyxerr.debugging(Debug::LATEX)) {
1681 features.showStruct();
1686 void Buffer::getLabelList(vector<docstring> & list) const
1688 // If this is a child document, use the parent's list instead.
1689 Buffer const * const pbuf = d->parent();
1691 pbuf->getLabelList(list);
1696 Toc & toc = d->toc_backend.toc("label");
1697 TocIterator toc_it = toc.begin();
1698 TocIterator end = toc.end();
1699 for (; toc_it != end; ++toc_it) {
1700 if (toc_it->depth() == 0)
1701 list.push_back(toc_it->str());
1706 void Buffer::updateBibfilesCache(UpdateScope scope) const
1708 // FIXME This is probably unnecssary, given where we call this.
1709 // If this is a child document, use the parent's cache instead.
1710 Buffer const * const pbuf = d->parent();
1711 if (pbuf && scope != UpdateChildOnly) {
1712 pbuf->updateBibfilesCache();
1716 d->bibfiles_cache_.clear();
1717 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1718 if (it->lyxCode() == BIBTEX_CODE) {
1719 InsetBibtex const & inset =
1720 static_cast<InsetBibtex const &>(*it);
1721 support::FileNameList const bibfiles = inset.getBibFiles();
1722 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1725 } else if (it->lyxCode() == INCLUDE_CODE) {
1726 InsetInclude & inset =
1727 static_cast<InsetInclude &>(*it);
1728 Buffer const * const incbuf = inset.getChildBuffer();
1731 support::FileNameList const & bibfiles =
1732 incbuf->getBibfilesCache(UpdateChildOnly);
1733 if (!bibfiles.empty()) {
1734 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1740 d->bibfile_cache_valid_ = true;
1741 d->bibinfo_cache_valid_ = false;
1745 void Buffer::invalidateBibinfoCache() const
1747 d->bibinfo_cache_valid_ = false;
1748 // also invalidate the cache for the parent buffer
1749 Buffer const * const pbuf = d->parent();
1751 pbuf->invalidateBibinfoCache();
1755 void Buffer::invalidateBibfileCache() const
1757 d->bibfile_cache_valid_ = false;
1758 d->bibinfo_cache_valid_ = false;
1759 // also invalidate the cache for the parent buffer
1760 Buffer const * const pbuf = d->parent();
1762 pbuf->invalidateBibfileCache();
1766 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1768 // FIXME This is probably unnecessary, given where we call this.
1769 // If this is a child document, use the master's cache instead.
1770 Buffer const * const pbuf = masterBuffer();
1771 if (pbuf != this && scope != UpdateChildOnly)
1772 return pbuf->getBibfilesCache();
1774 if (!d->bibfile_cache_valid_)
1775 this->updateBibfilesCache(scope);
1777 return d->bibfiles_cache_;
1781 BiblioInfo const & Buffer::masterBibInfo() const
1783 Buffer const * const tmp = masterBuffer();
1785 return tmp->masterBibInfo();
1790 void Buffer::checkBibInfoCache() const
1792 // use the master's cache
1793 Buffer const * const tmp = masterBuffer();
1795 tmp->checkBibInfoCache();
1799 // this will also reload the cache if it is invalid
1800 support::FileNameList const & bibfiles_cache = getBibfilesCache();
1802 // compare the cached timestamps with the actual ones.
1803 support::FileNameList::const_iterator ei = bibfiles_cache.begin();
1804 support::FileNameList::const_iterator en = bibfiles_cache.end();
1805 for (; ei != en; ++ ei) {
1806 time_t lastw = ei->lastModified();
1807 time_t prevw = d->bibfile_status_[*ei];
1808 if (lastw != prevw) {
1809 d->bibinfo_cache_valid_ = false;
1810 d->bibfile_status_[*ei] = lastw;
1814 // if not valid, then reload the info
1815 if (!d->bibinfo_cache_valid_) {
1816 d->bibinfo_.clear();
1817 fillWithBibKeys(d->bibinfo_);
1818 d->bibinfo_cache_valid_ = true;
1823 void Buffer::fillWithBibKeys(BiblioInfo & keys) const
1825 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1826 it->fillWithBibKeys(keys, it);
1830 bool Buffer::isDepClean(string const & name) const
1832 DepClean::const_iterator const it = d->dep_clean.find(name);
1833 if (it == d->dep_clean.end())
1839 void Buffer::markDepClean(string const & name)
1841 d->dep_clean[name] = true;
1845 bool Buffer::isExportableFormat(string const & format) const
1847 typedef vector<Format const *> Formats;
1849 formats = exportableFormats(true);
1850 Formats::const_iterator fit = formats.begin();
1851 Formats::const_iterator end = formats.end();
1852 for (; fit != end ; ++fit) {
1853 if ((*fit)->name() == format)
1860 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1863 // FIXME? if there is an Buffer LFUN that can be dispatched even
1864 // if internal, put a switch '(cmd.action)' here.
1870 switch (cmd.action()) {
1872 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1873 flag.setOnOff(isReadonly());
1876 // FIXME: There is need for a command-line import.
1877 //case LFUN_BUFFER_IMPORT:
1879 case LFUN_BUFFER_AUTO_SAVE:
1882 case LFUN_BUFFER_EXPORT_CUSTOM:
1883 // FIXME: Nothing to check here?
1886 case LFUN_BUFFER_EXPORT: {
1887 docstring const arg = cmd.argument();
1888 enable = arg == "custom" || isExportable(to_utf8(arg));
1890 flag.message(bformat(
1891 _("Don't know how to export to format: %1$s"), arg));
1895 case LFUN_BUFFER_CHKTEX:
1896 enable = isLatex() && !lyxrc.chktex_command.empty();
1899 case LFUN_BUILD_PROGRAM:
1900 enable = isExportable("program");
1903 case LFUN_BRANCH_ACTIVATE:
1904 case LFUN_BRANCH_DEACTIVATE: {
1905 BranchList const & branchList = params().branchlist();
1906 docstring const branchName = cmd.argument();
1907 enable = !branchName.empty() && branchList.find(branchName);
1911 case LFUN_BRANCH_ADD:
1912 case LFUN_BRANCHES_RENAME:
1913 case LFUN_BUFFER_PRINT:
1914 // if no Buffer is present, then of course we won't be called!
1917 case LFUN_BUFFER_LANGUAGE:
1918 enable = !isReadonly();
1924 flag.setEnabled(enable);
1929 void Buffer::dispatch(string const & command, DispatchResult & result)
1931 return dispatch(lyxaction.lookupFunc(command), result);
1935 // NOTE We can end up here even if we have no GUI, because we are called
1936 // by LyX::exec to handled command-line requests. So we may need to check
1937 // whether we have a GUI or not. The boolean use_gui holds this information.
1938 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1941 // FIXME? if there is an Buffer LFUN that can be dispatched even
1942 // if internal, put a switch '(cmd.action())' here.
1943 dr.dispatched(false);
1946 string const argument = to_utf8(func.argument());
1947 // We'll set this back to false if need be.
1948 bool dispatched = true;
1949 undo().beginUndoGroup();
1951 switch (func.action()) {
1952 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1953 if (lyxvc().inUse())
1954 lyxvc().toggleReadOnly();
1956 setReadonly(!isReadonly());
1959 case LFUN_BUFFER_EXPORT: {
1960 bool success = doExport(argument, false, false);
1961 dr.setError(!success);
1963 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1968 case LFUN_BUILD_PROGRAM:
1969 doExport("program", true, false);
1972 case LFUN_BUFFER_CHKTEX:
1976 case LFUN_BUFFER_EXPORT_CUSTOM: {
1978 string command = split(argument, format_name, ' ');
1979 Format const * format = formats.getFormat(format_name);
1981 lyxerr << "Format \"" << format_name
1982 << "\" not recognized!"
1987 // The name of the file created by the conversion process
1990 // Output to filename
1991 if (format->name() == "lyx") {
1992 string const latexname = latexName(false);
1993 filename = changeExtension(latexname,
1994 format->extension());
1995 filename = addName(temppath(), filename);
1997 if (!writeFile(FileName(filename)))
2001 doExport(format_name, true, false, filename);
2004 // Substitute $$FName for filename
2005 if (!contains(command, "$$FName"))
2006 command = "( " + command + " ) < $$FName";
2007 command = subst(command, "$$FName", filename);
2009 // Execute the command in the background
2011 call.startscript(Systemcall::DontWait, command);
2015 // FIXME: There is need for a command-line import.
2017 case LFUN_BUFFER_IMPORT:
2022 case LFUN_BUFFER_AUTO_SAVE:
2026 case LFUN_BRANCH_ADD: {
2027 docstring branch_name = func.argument();
2028 if (branch_name.empty()) {
2032 BranchList & branch_list = params().branchlist();
2033 vector<docstring> const branches =
2034 getVectorFromString(branch_name, branch_list.separator());
2036 for (vector<docstring>::const_iterator it = branches.begin();
2037 it != branches.end(); ++it) {
2039 Branch * branch = branch_list.find(branch_name);
2041 LYXERR0("Branch " << branch_name << " already exists.");
2045 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2047 branch_list.add(branch_name);
2048 branch = branch_list.find(branch_name);
2049 string const x11hexname = X11hexname(branch->color());
2050 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2051 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2053 dr.update(Update::Force);
2061 case LFUN_BRANCH_ACTIVATE:
2062 case LFUN_BRANCH_DEACTIVATE: {
2063 BranchList & branchList = params().branchlist();
2064 docstring const branchName = func.argument();
2065 // the case without a branch name is handled elsewhere
2066 if (branchName.empty()) {
2070 Branch * branch = branchList.find(branchName);
2072 LYXERR0("Branch " << branchName << " does not exist.");
2074 docstring const msg =
2075 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2078 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2080 dr.update(Update::Force);
2081 dr.forceBufferUpdate();
2086 case LFUN_BRANCHES_RENAME: {
2087 if (func.argument().empty())
2090 docstring const oldname = from_utf8(func.getArg(0));
2091 docstring const newname = from_utf8(func.getArg(1));
2092 InsetIterator it = inset_iterator_begin(inset());
2093 InsetIterator const end = inset_iterator_end(inset());
2094 bool success = false;
2095 for (; it != end; ++it) {
2096 if (it->lyxCode() == BRANCH_CODE) {
2097 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2098 if (ins.branch() == oldname) {
2099 undo().recordUndo(it);
2100 ins.rename(newname);
2105 if (it->lyxCode() == INCLUDE_CODE) {
2106 // get buffer of external file
2107 InsetInclude const & ins =
2108 static_cast<InsetInclude const &>(*it);
2109 Buffer * child = ins.getChildBuffer();
2112 child->dispatch(func, dr);
2117 dr.update(Update::Force);
2118 dr.forceBufferUpdate();
2123 case LFUN_BUFFER_PRINT: {
2124 // we'll assume there's a problem until we succeed
2126 string target = func.getArg(0);
2127 string target_name = func.getArg(1);
2128 string command = func.getArg(2);
2131 || target_name.empty()
2132 || command.empty()) {
2133 LYXERR0("Unable to parse " << func.argument());
2134 docstring const msg =
2135 bformat(_("Unable to parse \"%1$s\""), func.argument());
2139 if (target != "printer" && target != "file") {
2140 LYXERR0("Unrecognized target \"" << target << '"');
2141 docstring const msg =
2142 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2147 bool const update_unincluded =
2148 params().maintain_unincluded_children
2149 && !params().getIncludedChildren().empty();
2150 if (!doExport("dvi", true, update_unincluded)) {
2151 showPrintError(absFileName());
2152 dr.setMessage(_("Error exporting to DVI."));
2156 // Push directory path.
2157 string const path = temppath();
2158 // Prevent the compiler from optimizing away p
2162 // there are three cases here:
2163 // 1. we print to a file
2164 // 2. we print directly to a printer
2165 // 3. we print using a spool command (print to file first)
2168 string const dviname = changeExtension(latexName(true), "dvi");
2170 if (target == "printer") {
2171 if (!lyxrc.print_spool_command.empty()) {
2172 // case 3: print using a spool
2173 string const psname = changeExtension(dviname,".ps");
2174 command += ' ' + lyxrc.print_to_file
2177 + quoteName(dviname);
2179 string command2 = lyxrc.print_spool_command + ' ';
2180 if (target_name != "default") {
2181 command2 += lyxrc.print_spool_printerprefix
2185 command2 += quoteName(psname);
2187 // If successful, then spool command
2188 res = one.startscript(Systemcall::Wait, command);
2191 // If there's no GUI, we have to wait on this command. Otherwise,
2192 // LyX deletes the temporary directory, and with it the spooled
2193 // file, before it can be printed!!
2194 Systemcall::Starttype stype = use_gui ?
2195 Systemcall::DontWait : Systemcall::Wait;
2196 res = one.startscript(stype, command2);
2199 // case 2: print directly to a printer
2200 if (target_name != "default")
2201 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2203 Systemcall::Starttype stype = use_gui ?
2204 Systemcall::DontWait : Systemcall::Wait;
2205 res = one.startscript(stype, command + quoteName(dviname));
2209 // case 1: print to a file
2210 FileName const filename(makeAbsPath(target_name, filePath()));
2211 FileName const dvifile(makeAbsPath(dviname, path));
2212 if (filename.exists()) {
2213 docstring text = bformat(
2214 _("The file %1$s already exists.\n\n"
2215 "Do you want to overwrite that file?"),
2216 makeDisplayPath(filename.absFileName()));
2217 if (Alert::prompt(_("Overwrite file?"),
2218 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2221 command += ' ' + lyxrc.print_to_file
2222 + quoteName(filename.toFilesystemEncoding())
2224 + quoteName(dvifile.toFilesystemEncoding());
2226 Systemcall::Starttype stype = use_gui ?
2227 Systemcall::DontWait : Systemcall::Wait;
2228 res = one.startscript(stype, command);
2234 dr.setMessage(_("Error running external commands."));
2235 showPrintError(absFileName());
2240 case LFUN_BUFFER_LANGUAGE: {
2241 Language const * oldL = params().language;
2242 Language const * newL = languages.getLanguage(argument);
2243 if (!newL || oldL == newL)
2245 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2246 changeLanguage(oldL, newL);
2247 dr.forceBufferUpdate();
2256 dr.dispatched(dispatched);
2257 undo().endUndoGroup();
2261 void Buffer::changeLanguage(Language const * from, Language const * to)
2263 LASSERT(from, /**/);
2266 for_each(par_iterator_begin(),
2268 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2272 bool Buffer::isMultiLingual() const
2274 ParConstIterator end = par_iterator_end();
2275 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2276 if (it->isMultiLingual(params()))
2283 std::set<Language const *> Buffer::getLanguages() const
2285 std::set<Language const *> languages;
2286 getLanguages(languages);
2291 void Buffer::getLanguages(std::set<Language const *> & languages) const
2293 ParConstIterator end = par_iterator_end();
2294 // add the buffer language, even if it's not actively used
2295 languages.insert(language());
2296 // iterate over the paragraphs
2297 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2298 it->getLanguages(languages);
2300 std::vector<Buffer *> clist = getChildren();
2301 for (vector<Buffer *>::const_iterator cit = clist.begin();
2302 cit != clist.end(); ++cit)
2303 (*cit)->getLanguages(languages);
2307 DocIterator Buffer::getParFromID(int const id) const
2309 Buffer * buf = const_cast<Buffer *>(this);
2311 // John says this is called with id == -1 from undo
2312 lyxerr << "getParFromID(), id: " << id << endl;
2313 return doc_iterator_end(buf);
2316 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2317 if (it.paragraph().id() == id)
2320 return doc_iterator_end(buf);
2324 bool Buffer::hasParWithID(int const id) const
2326 return !getParFromID(id).atEnd();
2330 ParIterator Buffer::par_iterator_begin()
2332 return ParIterator(doc_iterator_begin(this));
2336 ParIterator Buffer::par_iterator_end()
2338 return ParIterator(doc_iterator_end(this));
2342 ParConstIterator Buffer::par_iterator_begin() const
2344 return ParConstIterator(doc_iterator_begin(this));
2348 ParConstIterator Buffer::par_iterator_end() const
2350 return ParConstIterator(doc_iterator_end(this));
2354 Language const * Buffer::language() const
2356 return params().language;
2360 docstring const Buffer::B_(string const & l10n) const
2362 return params().B_(l10n);
2366 bool Buffer::isClean() const
2368 return d->lyx_clean;
2372 bool Buffer::isExternallyModified(CheckMethod method) const
2374 LASSERT(d->filename.exists(), /**/);
2375 // if method == timestamp, check timestamp before checksum
2376 return (method == checksum_method
2377 || d->timestamp_ != d->filename.lastModified())
2378 && d->checksum_ != d->filename.checksum();
2382 void Buffer::saveCheckSum(FileName const & file) const
2384 if (file.exists()) {
2385 d->timestamp_ = file.lastModified();
2386 d->checksum_ = file.checksum();
2388 // in the case of save to a new file.
2395 void Buffer::markClean() const
2397 if (!d->lyx_clean) {
2398 d->lyx_clean = true;
2401 // if the .lyx file has been saved, we don't need an
2403 d->bak_clean = true;
2404 d->undo_.markDirty();
2408 void Buffer::setUnnamed(bool flag)
2414 bool Buffer::isUnnamed() const
2421 /// Don't check unnamed, here: isInternal() is used in
2422 /// newBuffer(), where the unnamed flag has not been set by anyone
2423 /// yet. Also, for an internal buffer, there should be no need for
2424 /// retrieving fileName() nor for checking if it is unnamed or not.
2425 bool Buffer::isInternal() const
2427 return fileName().extension() == "internal";
2431 void Buffer::markDirty()
2434 d->lyx_clean = false;
2437 d->bak_clean = false;
2439 DepClean::iterator it = d->dep_clean.begin();
2440 DepClean::const_iterator const end = d->dep_clean.end();
2442 for (; it != end; ++it)
2447 FileName Buffer::fileName() const
2453 string Buffer::absFileName() const
2455 return d->filename.absFileName();
2459 string Buffer::filePath() const
2461 return d->filename.onlyPath().absFileName() + "/";
2465 bool Buffer::isReadonly() const
2467 return d->read_only;
2471 void Buffer::setParent(Buffer const * buffer)
2473 // Avoids recursive include.
2474 d->setParent(buffer == this ? 0 : buffer);
2479 Buffer const * Buffer::parent() const
2485 void Buffer::Impl::collectRelatives(BufferSet & bufs) const
2487 bufs.insert(owner_);
2489 parent()->d->collectRelatives(bufs);
2491 // loop over children
2492 BufferPositionMap::const_iterator it = children_positions.begin();
2493 BufferPositionMap::const_iterator end = children_positions.end();
2494 for (; it != end; ++it)
2495 bufs.insert(const_cast<Buffer *>(it->first));
2499 std::vector<Buffer const *> Buffer::allRelatives() const
2502 d->collectRelatives(bufs);
2503 BufferSet::iterator it = bufs.begin();
2504 std::vector<Buffer const *> ret;
2505 for (; it != bufs.end(); ++it)
2511 Buffer const * Buffer::masterBuffer() const
2513 Buffer const * const pbuf = d->parent();
2517 return pbuf->masterBuffer();
2521 bool Buffer::isChild(Buffer * child) const
2523 return d->children_positions.find(child) != d->children_positions.end();
2527 DocIterator Buffer::firstChildPosition(Buffer const * child)
2529 Impl::BufferPositionMap::iterator it;
2530 it = d->children_positions.find(child);
2531 if (it == d->children_positions.end())
2532 return DocIterator(this);
2537 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2539 // loop over children
2540 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2541 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2542 for (; it != end; ++it) {
2543 Buffer * child = const_cast<Buffer *>(it->first);
2544 clist.push_back(child);
2545 if (grand_children) {
2546 // there might be grandchildren
2547 vector<Buffer *> glist = child->getChildren();
2548 clist.insert(clist.end(), glist.begin(), glist.end());
2554 vector<Buffer *> Buffer::getChildren(bool grand_children) const
2557 getChildren(v, grand_children);
2562 template<typename M>
2563 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2568 typename M::const_iterator it = m.lower_bound(x);
2569 if (it == m.begin())
2577 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2578 DocIterator const & pos) const
2580 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2582 // if paragraphs have no macro context set, pos will be empty
2586 // we haven't found anything yet
2587 DocIterator bestPos = owner_->par_iterator_begin();
2588 MacroData const * bestData = 0;
2590 // find macro definitions for name
2591 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2592 if (nameIt != macros.end()) {
2593 // find last definition in front of pos or at pos itself
2594 PositionScopeMacroMap::const_iterator it
2595 = greatest_below(nameIt->second, pos);
2596 if (it != nameIt->second.end()) {
2598 // scope ends behind pos?
2599 if (pos < it->second.first) {
2600 // Looks good, remember this. If there
2601 // is no external macro behind this,
2602 // we found the right one already.
2603 bestPos = it->first;
2604 bestData = &it->second.second;
2608 // try previous macro if there is one
2609 if (it == nameIt->second.begin())
2616 // find macros in included files
2617 PositionScopeBufferMap::const_iterator it
2618 = greatest_below(position_to_children, pos);
2619 if (it == position_to_children.end())
2620 // no children before
2624 // do we know something better (i.e. later) already?
2625 if (it->first < bestPos )
2628 // scope ends behind pos?
2629 if (pos < it->second.first) {
2630 // look for macro in external file
2632 MacroData const * data
2633 = it->second.second->getMacro(name, false);
2636 bestPos = it->first;
2642 // try previous file if there is one
2643 if (it == position_to_children.begin())
2648 // return the best macro we have found
2653 MacroData const * Buffer::getMacro(docstring const & name,
2654 DocIterator const & pos, bool global) const
2659 // query buffer macros
2660 MacroData const * data = d->getBufferMacro(name, pos);
2664 // If there is a master buffer, query that
2665 Buffer const * const pbuf = d->parent();
2667 d->macro_lock = true;
2668 MacroData const * macro = pbuf->getMacro(
2669 name, *this, false);
2670 d->macro_lock = false;
2676 data = MacroTable::globalMacros().get(name);
2685 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2687 // set scope end behind the last paragraph
2688 DocIterator scope = par_iterator_begin();
2689 scope.pit() = scope.lastpit() + 1;
2691 return getMacro(name, scope, global);
2695 MacroData const * Buffer::getMacro(docstring const & name,
2696 Buffer const & child, bool global) const
2698 // look where the child buffer is included first
2699 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2700 if (it == d->children_positions.end())
2703 // check for macros at the inclusion position
2704 return getMacro(name, it->second, global);
2708 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2710 pit_type const lastpit = it.lastpit();
2712 // look for macros in each paragraph
2713 while (it.pit() <= lastpit) {
2714 Paragraph & par = it.paragraph();
2716 // iterate over the insets of the current paragraph
2717 InsetList const & insets = par.insetList();
2718 InsetList::const_iterator iit = insets.begin();
2719 InsetList::const_iterator end = insets.end();
2720 for (; iit != end; ++iit) {
2721 it.pos() = iit->pos;
2723 // is it a nested text inset?
2724 if (iit->inset->asInsetText()) {
2725 // Inset needs its own scope?
2726 InsetText const * itext = iit->inset->asInsetText();
2727 bool newScope = itext->isMacroScope();
2729 // scope which ends just behind the inset
2730 DocIterator insetScope = it;
2733 // collect macros in inset
2734 it.push_back(CursorSlice(*iit->inset));
2735 updateMacros(it, newScope ? insetScope : scope);
2740 // is it an external file?
2741 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2742 // get buffer of external file
2743 InsetInclude const & inset =
2744 static_cast<InsetInclude const &>(*iit->inset);
2746 Buffer * child = inset.getChildBuffer();
2751 // register its position, but only when it is
2752 // included first in the buffer
2753 if (children_positions.find(child) ==
2754 children_positions.end())
2755 children_positions[child] = it;
2757 // register child with its scope
2758 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2762 if (doing_export && iit->inset->asInsetMath()) {
2763 InsetMath * im = static_cast<InsetMath *>(iit->inset);
2764 if (im->asHullInset()) {
2765 InsetMathHull * hull = static_cast<InsetMathHull *>(im);
2766 hull->recordLocation(it);
2770 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2774 MathMacroTemplate & macroTemplate =
2775 static_cast<MathMacroTemplate &>(*iit->inset);
2776 MacroContext mc(owner_, it);
2777 macroTemplate.updateToContext(mc);
2780 bool valid = macroTemplate.validMacro();
2781 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2782 // then the BufferView's cursor will be invalid in
2783 // some cases which leads to crashes.
2788 // FIXME (Abdel), I don't understandt why we pass 'it' here
2789 // instead of 'macroTemplate' defined above... is this correct?
2790 macros[macroTemplate.name()][it] =
2791 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2801 void Buffer::updateMacros() const
2806 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2808 // start with empty table
2810 d->children_positions.clear();
2811 d->position_to_children.clear();
2813 // Iterate over buffer, starting with first paragraph
2814 // The scope must be bigger than any lookup DocIterator
2815 // later. For the global lookup, lastpit+1 is used, hence
2816 // we use lastpit+2 here.
2817 DocIterator it = par_iterator_begin();
2818 DocIterator outerScope = it;
2819 outerScope.pit() = outerScope.lastpit() + 2;
2820 d->updateMacros(it, outerScope);
2824 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2826 InsetIterator it = inset_iterator_begin(inset());
2827 InsetIterator const end = inset_iterator_end(inset());
2828 for (; it != end; ++it) {
2829 if (it->lyxCode() == BRANCH_CODE) {
2830 InsetBranch & br = static_cast<InsetBranch &>(*it);
2831 docstring const name = br.branch();
2832 if (!from_master && !params().branchlist().find(name))
2833 result.push_back(name);
2834 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2835 result.push_back(name);
2838 if (it->lyxCode() == INCLUDE_CODE) {
2839 // get buffer of external file
2840 InsetInclude const & ins =
2841 static_cast<InsetInclude const &>(*it);
2842 Buffer * child = ins.getChildBuffer();
2845 child->getUsedBranches(result, true);
2848 // remove duplicates
2853 void Buffer::updateMacroInstances() const
2855 LYXERR(Debug::MACROS, "updateMacroInstances for "
2856 << d->filename.onlyFileName());
2857 DocIterator it = doc_iterator_begin(this);
2859 DocIterator const end = doc_iterator_end(this);
2860 for (; it != end; it.forwardInset()) {
2861 // look for MathData cells in InsetMathNest insets
2862 InsetMath * minset = it.nextInset()->asInsetMath();
2866 // update macro in all cells of the InsetMathNest
2867 DocIterator::idx_type n = minset->nargs();
2868 MacroContext mc = MacroContext(this, it);
2869 for (DocIterator::idx_type i = 0; i < n; ++i) {
2870 MathData & data = minset->cell(i);
2871 data.updateMacros(0, mc);
2877 void Buffer::listMacroNames(MacroNameSet & macros) const
2882 d->macro_lock = true;
2884 // loop over macro names
2885 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2886 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2887 for (; nameIt != nameEnd; ++nameIt)
2888 macros.insert(nameIt->first);
2890 // loop over children
2891 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2892 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2893 for (; it != end; ++it)
2894 it->first->listMacroNames(macros);
2897 Buffer const * const pbuf = d->parent();
2899 pbuf->listMacroNames(macros);
2901 d->macro_lock = false;
2905 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2907 Buffer const * const pbuf = d->parent();
2912 pbuf->listMacroNames(names);
2915 MacroNameSet::iterator it = names.begin();
2916 MacroNameSet::iterator end = names.end();
2917 for (; it != end; ++it) {
2919 MacroData const * data =
2920 pbuf->getMacro(*it, *this, false);
2922 macros.insert(data);
2924 // we cannot access the original MathMacroTemplate anymore
2925 // here to calls validate method. So we do its work here manually.
2926 // FIXME: somehow make the template accessible here.
2927 if (data->optionals() > 0)
2928 features.require("xargs");
2934 Buffer::References & Buffer::references(docstring const & label)
2937 return const_cast<Buffer *>(masterBuffer())->references(label);
2939 RefCache::iterator it = d->ref_cache_.find(label);
2940 if (it != d->ref_cache_.end())
2941 return it->second.second;
2943 static InsetLabel const * dummy_il = 0;
2944 static References const dummy_refs;
2945 it = d->ref_cache_.insert(
2946 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2947 return it->second.second;
2951 Buffer::References const & Buffer::references(docstring const & label) const
2953 return const_cast<Buffer *>(this)->references(label);
2957 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2959 masterBuffer()->d->ref_cache_[label].first = il;
2963 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2965 return masterBuffer()->d->ref_cache_[label].first;
2969 void Buffer::clearReferenceCache() const
2972 d->ref_cache_.clear();
2976 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2979 //FIXME: This does not work for child documents yet.
2980 LASSERT(code == CITE_CODE, /**/);
2981 // Check if the label 'from' appears more than once
2982 vector<docstring> labels;
2984 checkBibInfoCache();
2985 BiblioInfo const & keys = masterBibInfo();
2986 BiblioInfo::const_iterator bit = keys.begin();
2987 BiblioInfo::const_iterator bend = keys.end();
2989 for (; bit != bend; ++bit)
2991 labels.push_back(bit->first);
2994 if (count(labels.begin(), labels.end(), from) > 1)
2997 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2998 if (it->lyxCode() == code) {
2999 InsetCommand & inset = static_cast<InsetCommand &>(*it);
3000 docstring const oldValue = inset.getParam(paramName);
3001 if (oldValue == from)
3002 inset.setParam(paramName, to);
3008 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
3009 pit_type par_end, bool full_source) const
3011 OutputParams runparams(¶ms().encoding());
3012 runparams.nice = true;
3013 runparams.flavor = params().useXetex ?
3014 OutputParams::XETEX : OutputParams::LATEX;
3015 runparams.linelen = lyxrc.plaintext_linelen;
3016 // No side effect of file copying and image conversion
3017 runparams.dryrun = true;
3020 os << "% " << _("Preview source code") << "\n\n";
3022 d->texrow.newline();
3023 d->texrow.newline();
3025 writeDocBookSource(os, absFileName(), runparams, false);
3027 // latex or literate
3028 writeLaTeXSource(os, string(), runparams, true, true);
3030 runparams.par_begin = par_begin;
3031 runparams.par_end = par_end;
3032 if (par_begin + 1 == par_end) {
3034 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3038 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3039 convert<docstring>(par_begin),
3040 convert<docstring>(par_end - 1))
3047 // output paragraphs
3049 docbookParagraphs(text(), *this, os, runparams);
3051 // latex or literate
3052 latexParagraphs(*this, text(), os, texrow, runparams);
3057 ErrorList & Buffer::errorList(string const & type) const
3059 static ErrorList emptyErrorList;
3060 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3061 if (it == d->errorLists.end())
3062 return emptyErrorList;
3068 void Buffer::updateTocItem(std::string const & type,
3069 DocIterator const & dit) const
3072 d->gui_->updateTocItem(type, dit);
3076 void Buffer::structureChanged() const
3079 d->gui_->structureChanged();
3083 void Buffer::errors(string const & err, bool from_master) const
3086 d->gui_->errors(err, from_master);
3090 void Buffer::message(docstring const & msg) const
3093 d->gui_->message(msg);
3097 void Buffer::setBusy(bool on) const
3100 d->gui_->setBusy(on);
3104 void Buffer::updateTitles() const
3107 d->wa_->updateTitles();
3111 void Buffer::resetAutosaveTimers() const
3114 d->gui_->resetAutosaveTimers();
3118 bool Buffer::hasGuiDelegate() const
3124 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3133 class AutoSaveBuffer : public ForkedProcess {
3136 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3137 : buffer_(buffer), fname_(fname) {}
3139 virtual shared_ptr<ForkedProcess> clone() const
3141 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3146 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3147 from_utf8(fname_.absFileName())));
3148 return run(DontWait);
3152 virtual int generateChild();
3154 Buffer const & buffer_;
3159 int AutoSaveBuffer::generateChild()
3161 #if defined(__APPLE__)
3162 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3163 * We should use something else like threads.
3165 * Since I do not know how to determine at run time what is the OS X
3166 * version, I just disable forking altogether for now (JMarc)
3168 pid_t const pid = -1;
3170 // tmp_ret will be located (usually) in /tmp
3171 // will that be a problem?
3172 // Note that this calls ForkedCalls::fork(), so it's
3173 // ok cross-platform.
3174 pid_t const pid = fork();
3175 // If you want to debug the autosave
3176 // you should set pid to -1, and comment out the fork.
3177 if (pid != 0 && pid != -1)
3181 // pid = -1 signifies that lyx was unable
3182 // to fork. But we will do the save
3184 bool failed = false;
3185 FileName const tmp_ret = FileName::tempName("lyxauto");
3186 if (!tmp_ret.empty()) {
3187 buffer_.writeFile(tmp_ret);
3188 // assume successful write of tmp_ret
3189 if (!tmp_ret.moveTo(fname_))
3195 // failed to write/rename tmp_ret so try writing direct
3196 if (!buffer_.writeFile(fname_)) {
3197 // It is dangerous to do this in the child,
3198 // but safe in the parent, so...
3199 if (pid == -1) // emit message signal.
3200 buffer_.message(_("Autosave failed!"));
3204 if (pid == 0) // we are the child so...
3213 FileName Buffer::getAutosaveFileName() const
3215 // if the document is unnamed try to save in the backup dir, else
3216 // in the default document path, and as a last try in the filePath,
3217 // which will most often be the temporary directory
3220 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3221 : lyxrc.backupdir_path;
3222 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3225 string const fname = "#" + d->filename.onlyFileName() + "#";
3226 return makeAbsPath(fname, fpath);
3230 void Buffer::removeAutosaveFile() const
3232 FileName const f = getAutosaveFileName();
3238 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3240 FileName const newauto = getAutosaveFileName();
3242 if (newauto != oldauto && oldauto.exists())
3243 if (!oldauto.moveTo(newauto))
3244 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3248 // Perfect target for a thread...
3249 void Buffer::autoSave() const
3251 if (d->bak_clean || isReadonly()) {
3252 // We don't save now, but we'll try again later
3253 resetAutosaveTimers();
3257 // emit message signal.
3258 message(_("Autosaving current document..."));
3259 AutoSaveBuffer autosave(*this, getAutosaveFileName());
3262 d->bak_clean = true;
3264 resetAutosaveTimers();
3268 string Buffer::bufferFormat() const
3270 string format = params().documentClass().outputFormat();
3271 if (format == "latex") {
3272 if (params().useXetex)
3274 if (params().encoding().package() == Encoding::japanese)
3281 string Buffer::getDefaultOutputFormat() const
3283 if (!params().defaultOutputFormat.empty()
3284 && params().defaultOutputFormat != "default")
3285 return params().defaultOutputFormat;
3286 typedef vector<Format const *> Formats;
3287 Formats formats = exportableFormats(true);
3290 || params().useXetex
3291 || params().encoding().package() == Encoding::japanese) {
3292 if (formats.empty())
3294 // return the first we find
3295 return formats.front()->name();
3297 return lyxrc.default_view_format;
3302 // helper class, to guarantee this gets reset properly
3303 class MarkAsExporting {
3305 MarkAsExporting(Buffer const * buf) : buf_(buf)
3307 LASSERT(buf_, /* */);
3308 buf_->setExportStatus(true);
3312 buf_->setExportStatus(false);
3315 Buffer const * const buf_;
3320 void Buffer::setExportStatus(bool e) const
3322 d->doing_export = e;
3326 bool Buffer::isExporting() const
3328 return d->doing_export;
3332 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3333 bool includeall, string & result_file) const
3335 MarkAsExporting exporting(this);
3336 string backend_format;
3337 OutputParams runparams(¶ms().encoding());
3338 runparams.flavor = OutputParams::LATEX;
3339 runparams.linelen = lyxrc.plaintext_linelen;
3340 runparams.includeall = includeall;
3341 vector<string> backs = backends();
3342 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3343 // Get shortest path to format
3344 Graph::EdgePath path;
3345 for (vector<string>::const_iterator it = backs.begin();
3346 it != backs.end(); ++it) {
3347 Graph::EdgePath p = theConverters().getPath(*it, format);
3348 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3349 backend_format = *it;
3354 if (!put_in_tempdir) {
3355 // Only show this alert if this is an export to a non-temporary
3356 // file (not for previewing).
3357 Alert::error(_("Couldn't export file"), bformat(
3358 _("No information for exporting the format %1$s."),
3359 formats.prettyName(format)));
3363 runparams.flavor = theConverters().getFlavor(path);
3366 backend_format = format;
3367 // FIXME: Don't hardcode format names here, but use a flag
3368 if (backend_format == "pdflatex")
3369 runparams.flavor = OutputParams::PDFLATEX;
3372 string filename = latexName(false);
3373 filename = addName(temppath(), filename);
3374 filename = changeExtension(filename,
3375 formats.extension(backend_format));
3378 updateMacroInstances();
3380 // Plain text backend
3381 if (backend_format == "text") {
3382 runparams.flavor = OutputParams::TEXT;
3383 writePlaintextFile(*this, FileName(filename), runparams);
3386 else if (backend_format == "xhtml") {
3387 runparams.flavor = OutputParams::HTML;
3388 switch (params().html_math_output) {
3389 case BufferParams::MathML:
3390 runparams.math_flavor = OutputParams::MathAsMathML;
3392 case BufferParams::HTML:
3393 runparams.math_flavor = OutputParams::MathAsHTML;
3395 case BufferParams::Images:
3396 runparams.math_flavor = OutputParams::MathAsImages;
3398 case BufferParams::LaTeX:
3399 runparams.math_flavor = OutputParams::MathAsLaTeX;
3403 makeLyXHTMLFile(FileName(filename), runparams);
3404 } else if (backend_format == "lyx")
3405 writeFile(FileName(filename));
3407 else if (isDocBook()) {
3408 runparams.nice = !put_in_tempdir;
3409 makeDocBookFile(FileName(filename), runparams);
3412 else if (backend_format == format) {
3413 runparams.nice = true;
3414 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3416 } else if (!lyxrc.tex_allows_spaces
3417 && contains(filePath(), ' ')) {
3418 Alert::error(_("File name error"),
3419 _("The directory path to the document cannot contain spaces."));
3422 runparams.nice = false;
3423 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3427 string const error_type = (format == "program")
3428 ? "Build" : bufferFormat();
3429 ErrorList & error_list = d->errorLists[error_type];
3430 string const ext = formats.extension(format);
3431 FileName const tmp_result_file(changeExtension(filename, ext));
3432 bool const success = theConverters().convert(this, FileName(filename),
3433 tmp_result_file, FileName(absFileName()), backend_format, format,
3436 // Emit the signal to show the error list or copy it back to the
3437 // cloned Buffer so that it cab be emitted afterwards.
3438 if (format != backend_format) {
3439 if (d->cloned_buffer_) {
3440 d->cloned_buffer_->d->errorLists[error_type] =
3441 d->errorLists[error_type];
3444 // also to the children, in case of master-buffer-view
3445 std::vector<Buffer *> clist = getChildren();
3446 for (vector<Buffer *>::const_iterator cit = clist.begin();
3447 cit != clist.end(); ++cit) {
3448 if (d->cloned_buffer_) {
3449 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3450 (*cit)->d->errorLists[error_type];
3452 (*cit)->errors(error_type, true);
3456 if (d->cloned_buffer_) {
3457 // Enable reverse dvi or pdf to work by copying back the texrow
3458 // object to the cloned buffer.
3459 // FIXME: There is a possibility of concurrent access to texrow
3460 // here from the main GUI thread that should be securized.
3461 d->cloned_buffer_->d->texrow = d->texrow;
3462 string const error_type = bufferFormat();
3463 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3469 if (put_in_tempdir) {
3470 result_file = tmp_result_file.absFileName();
3474 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3475 // We need to copy referenced files (e. g. included graphics
3476 // if format == "dvi") to the result dir.
3477 vector<ExportedFile> const files =
3478 runparams.exportdata->externalFiles(format);
3479 string const dest = onlyPath(result_file);
3480 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3481 : force_overwrite == ALL_FILES;
3482 CopyStatus status = use_force ? FORCE : SUCCESS;
3484 vector<ExportedFile>::const_iterator it = files.begin();
3485 vector<ExportedFile>::const_iterator const en = files.end();
3486 for (; it != en && status != CANCEL; ++it) {
3487 string const fmt = formats.getFormatFromFile(it->sourceName);
3488 status = copyFile(fmt, it->sourceName,
3489 makeAbsPath(it->exportName, dest),
3490 it->exportName, status == FORCE);
3493 if (status == CANCEL) {
3494 message(_("Document export cancelled."));
3495 } else if (tmp_result_file.exists()) {
3496 // Finally copy the main file
3497 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3498 : force_overwrite != NO_FILES;
3499 if (status == SUCCESS && use_force)
3501 status = copyFile(format, tmp_result_file,
3502 FileName(result_file), result_file,
3504 message(bformat(_("Document exported as %1$s "
3506 formats.prettyName(format),
3507 makeDisplayPath(result_file)));
3509 // This must be a dummy converter like fax (bug 1888)
3510 message(bformat(_("Document exported as %1$s"),
3511 formats.prettyName(format)));
3518 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3519 bool includeall) const
3522 // (1) export with all included children (omit \includeonly)
3523 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3525 // (2) export with included children only
3526 return doExport(format, put_in_tempdir, false, result_file);
3530 bool Buffer::preview(string const & format, bool includeall) const
3532 MarkAsExporting exporting(this);
3534 // (1) export with all included children (omit \includeonly)
3535 if (includeall && !doExport(format, true, true))
3537 // (2) export with included children only
3538 if (!doExport(format, true, false, result_file))
3540 return formats.view(*this, FileName(result_file), format);
3544 bool Buffer::isExportable(string const & format) const
3546 vector<string> backs = backends();
3547 for (vector<string>::const_iterator it = backs.begin();
3548 it != backs.end(); ++it)
3549 if (theConverters().isReachable(*it, format))
3555 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3557 vector<string> const backs = backends();
3558 vector<Format const *> result =
3559 theConverters().getReachable(backs[0], only_viewable, true);
3560 for (vector<string>::const_iterator it = backs.begin() + 1;
3561 it != backs.end(); ++it) {
3562 vector<Format const *> r =
3563 theConverters().getReachable(*it, only_viewable, false);
3564 result.insert(result.end(), r.begin(), r.end());
3570 vector<string> Buffer::backends() const
3573 v.push_back(bufferFormat());
3574 // FIXME: Don't hardcode format names here, but use a flag
3575 if (v.back() == "latex")
3576 v.push_back("pdflatex");
3577 v.push_back("xhtml");
3578 v.push_back("text");
3584 bool Buffer::readFileHelper(FileName const & s)
3586 // File information about normal file
3588 docstring const file = makeDisplayPath(s.absFileName(), 50);
3589 docstring text = bformat(_("The specified document\n%1$s"
3590 "\ncould not be read."), file);
3591 Alert::error(_("Could not read document"), text);
3595 // Check if emergency save file exists and is newer.
3596 FileName const e(s.absFileName() + ".emergency");
3598 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3599 docstring const file = makeDisplayPath(s.absFileName(), 20);
3600 docstring const text =
3601 bformat(_("An emergency save of the document "
3603 "Recover emergency save?"), file);
3604 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3605 _("&Recover"), _("&Load Original"),
3609 // the file is not saved if we load the emergency file.
3614 if ((res = readFile(e)) == success)
3615 str = _("Document was successfully recovered.");
3617 str = _("Document was NOT successfully recovered.");
3618 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3619 makeDisplayPath(e.absFileName()));
3621 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3622 _("&Remove"), _("&Keep it"))) {
3625 Alert::warning(_("Emergency file deleted"),
3626 _("Do not forget to save your file now!"), true);
3631 if (!Alert::prompt(_("Delete emergency file?"),
3632 _("Remove emergency file now?"), 1, 1,
3633 _("&Remove"), _("&Keep it")))
3641 // Now check if autosave file is newer.
3642 FileName const a(onlyPath(s.absFileName()) + '#' + onlyFileName(s.absFileName()) + '#');
3644 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3645 docstring const file = makeDisplayPath(s.absFileName(), 20);
3646 docstring const text =
3647 bformat(_("The backup of the document "
3648 "%1$s is newer.\n\nLoad the "
3649 "backup instead?"), file);
3650 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3651 _("&Load backup"), _("Load &original"),
3655 // the file is not saved if we load the autosave file.
3659 // Here we delete the autosave
3670 bool Buffer::loadLyXFile(FileName const & s)
3672 // If the file is not readable, we try to
3673 // retrieve the file from version control.
3674 if (!s.isReadableFile()
3675 && !LyXVC::file_not_found_hook(s))
3678 if (s.isReadableFile()){
3679 // InsetInfo needs to know if file is under VCS
3680 lyxvc().file_found_hook(s);
3681 if (readFileHelper(s)) {
3682 d->read_only = !s.isWritable();
3690 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3692 TeXErrors::Errors::const_iterator cit = terr.begin();
3693 TeXErrors::Errors::const_iterator end = terr.end();
3695 for (; cit != end; ++cit) {
3698 int errorRow = cit->error_in_line;
3699 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3705 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3706 } while (found && id_start == id_end && pos_start == pos_end);
3708 errorList.push_back(ErrorItem(cit->error_desc,
3709 cit->error_text, id_start, pos_start, pos_end));
3714 void Buffer::setBuffersForInsets() const
3716 inset().setBuffer(const_cast<Buffer &>(*this));
3720 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3722 // Use the master text class also for child documents
3723 Buffer const * const master = masterBuffer();
3724 DocumentClass const & textclass = master->params().documentClass();
3726 // do this only if we are the top-level Buffer
3728 checkBibInfoCache();
3730 // keep the buffers to be children in this set. If the call from the
3731 // master comes back we can see which of them were actually seen (i.e.
3732 // via an InsetInclude). The remaining ones in the set need still be updated.
3733 static std::set<Buffer const *> bufToUpdate;
3734 if (scope == UpdateMaster) {
3735 // If this is a child document start with the master
3736 if (master != this) {
3737 bufToUpdate.insert(this);
3738 master->updateBuffer(UpdateMaster, utype);
3739 // Do this here in case the master has no gui associated with it. Then,
3740 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3741 if (!master->d->gui_)
3744 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3745 if (bufToUpdate.find(this) == bufToUpdate.end())
3749 // start over the counters in the master
3750 textclass.counters().reset();
3753 // update will be done below for this buffer
3754 bufToUpdate.erase(this);
3756 // update all caches
3757 clearReferenceCache();
3760 Buffer & cbuf = const_cast<Buffer &>(*this);
3762 LASSERT(!text().paragraphs().empty(), /**/);
3765 ParIterator parit = cbuf.par_iterator_begin();
3766 updateBuffer(parit, utype);
3769 // TocBackend update will be done later.
3772 cbuf.tocBackend().update();
3773 if (scope == UpdateMaster)
3774 cbuf.structureChanged();
3778 static depth_type getDepth(DocIterator const & it)
3780 depth_type depth = 0;
3781 for (size_t i = 0 ; i < it.depth() ; ++i)
3782 if (!it[i].inset().inMathed())
3783 depth += it[i].paragraph().getDepth() + 1;
3784 // remove 1 since the outer inset does not count
3788 static depth_type getItemDepth(ParIterator const & it)
3790 Paragraph const & par = *it;
3791 LabelType const labeltype = par.layout().labeltype;
3793 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3796 // this will hold the lowest depth encountered up to now.
3797 depth_type min_depth = getDepth(it);
3798 ParIterator prev_it = it;
3801 --prev_it.top().pit();
3803 // start of nested inset: go to outer par
3805 if (prev_it.empty()) {
3806 // start of document: nothing to do
3811 // We search for the first paragraph with same label
3812 // that is not more deeply nested.
3813 Paragraph & prev_par = *prev_it;
3814 depth_type const prev_depth = getDepth(prev_it);
3815 if (labeltype == prev_par.layout().labeltype) {
3816 if (prev_depth < min_depth)
3817 return prev_par.itemdepth + 1;
3818 if (prev_depth == min_depth)
3819 return prev_par.itemdepth;
3821 min_depth = min(min_depth, prev_depth);
3822 // small optimization: if we are at depth 0, we won't
3823 // find anything else
3824 if (prev_depth == 0)
3830 static bool needEnumCounterReset(ParIterator const & it)
3832 Paragraph const & par = *it;
3833 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3834 depth_type const cur_depth = par.getDepth();
3835 ParIterator prev_it = it;
3836 while (prev_it.pit()) {
3837 --prev_it.top().pit();
3838 Paragraph const & prev_par = *prev_it;
3839 if (prev_par.getDepth() <= cur_depth)
3840 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3842 // start of nested inset: reset
3847 // set the label of a paragraph. This includes the counters.
3848 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3850 BufferParams const & bp = owner_->masterBuffer()->params();
3851 DocumentClass const & textclass = bp.documentClass();
3852 Paragraph & par = it.paragraph();
3853 Layout const & layout = par.layout();
3854 Counters & counters = textclass.counters();
3856 if (par.params().startOfAppendix()) {
3857 // FIXME: only the counter corresponding to toplevel
3858 // sectioning should be reset
3860 counters.appendix(true);
3862 par.params().appendix(counters.appendix());
3864 // Compute the item depth of the paragraph
3865 par.itemdepth = getItemDepth(it);
3867 if (layout.margintype == MARGIN_MANUAL
3868 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3869 if (par.params().labelWidthString().empty())
3870 par.params().labelWidthString(par.expandLabel(layout, bp));
3872 par.params().labelWidthString(docstring());
3875 switch(layout.labeltype) {
3877 if (layout.toclevel <= bp.secnumdepth
3878 && (layout.latextype != LATEX_ENVIRONMENT
3879 || it.text()->isFirstInSequence(it.pit()))) {
3880 counters.step(layout.counter, utype);
3881 par.params().labelString(
3882 par.expandLabel(layout, bp));
3884 par.params().labelString(docstring());
3887 case LABEL_ITEMIZE: {
3888 // At some point of time we should do something more
3889 // clever here, like:
3890 // par.params().labelString(
3891 // bp.user_defined_bullet(par.itemdepth).getText());
3892 // for now, use a simple hardcoded label
3893 docstring itemlabel;
3894 switch (par.itemdepth) {
3896 itemlabel = char_type(0x2022);
3899 itemlabel = char_type(0x2013);
3902 itemlabel = char_type(0x2217);
3905 itemlabel = char_type(0x2219); // or 0x00b7
3908 par.params().labelString(itemlabel);
3912 case LABEL_ENUMERATE: {
3913 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3915 switch (par.itemdepth) {
3924 enumcounter += "iv";
3927 // not a valid enumdepth...
3931 // Maybe we have to reset the enumeration counter.
3932 if (needEnumCounterReset(it))
3933 counters.reset(enumcounter);
3934 counters.step(enumcounter, utype);
3936 string const & lang = par.getParLanguage(bp)->code();
3937 par.params().labelString(counters.theCounter(enumcounter, lang));
3942 case LABEL_SENSITIVE: {
3943 string const & type = counters.current_float();
3944 docstring full_label;
3946 full_label = owner_->B_("Senseless!!! ");
3948 docstring name = owner_->B_(textclass.floats().getType(type).name());
3949 if (counters.hasCounter(from_utf8(type))) {
3950 string const & lang = par.getParLanguage(bp)->code();
3951 counters.step(from_utf8(type), utype);
3952 full_label = bformat(from_ascii("%1$s %2$s:"),
3954 counters.theCounter(from_utf8(type), lang));
3956 full_label = bformat(from_ascii("%1$s #:"), name);
3958 par.params().labelString(full_label);
3962 case LABEL_NO_LABEL:
3963 par.params().labelString(docstring());
3967 case LABEL_TOP_ENVIRONMENT:
3968 case LABEL_CENTERED_TOP_ENVIRONMENT:
3971 par.params().labelString(par.expandLabel(layout, bp));
3977 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
3979 LASSERT(parit.pit() == 0, /**/);
3981 // set the position of the text in the buffer to be able
3982 // to resolve macros in it. This has nothing to do with
3983 // labels, but by putting it here we avoid implementing
3984 // a whole bunch of traversal routines just for this call.
3985 parit.text()->setMacrocontextPosition(parit);
3987 depth_type maxdepth = 0;
3988 pit_type const lastpit = parit.lastpit();
3989 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3990 // reduce depth if necessary
3991 parit->params().depth(min(parit->params().depth(), maxdepth));
3992 maxdepth = parit->getMaxDepthAfter();
3994 if (utype == OutputUpdate) {
3995 // track the active counters
3996 // we have to do this for the master buffer, since the local
3997 // buffer isn't tracking anything.
3998 masterBuffer()->params().documentClass().counters().
3999 setActiveLayout(parit->layout());
4002 // set the counter for this paragraph
4003 d->setLabel(parit, utype);
4006 InsetList::const_iterator iit = parit->insetList().begin();
4007 InsetList::const_iterator end = parit->insetList().end();
4008 for (; iit != end; ++iit) {
4009 parit.pos() = iit->pos;
4010 iit->inset->updateBuffer(parit, utype);
4016 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4017 WordLangTuple & word_lang, docstring_list & suggestions) const
4021 suggestions.clear();
4022 word_lang = WordLangTuple();
4023 // OK, we start from here.
4024 DocIterator const end = doc_iterator_end(this);
4025 for (; from != end; from.forwardPos()) {
4026 // We are only interested in text so remove the math CursorSlice.
4027 while (from.inMathed()) {
4031 // If from is at the end of the document (which is possible
4032 // when leaving the mathed) LyX will crash later.
4036 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4037 if (SpellChecker::misspelled(res)) {
4042 // Do not increase progress when from == to, otherwise the word
4043 // count will be wrong.
4053 bool Buffer::reload()
4057 removeAutosaveFile();
4058 // e.g., read-only status could have changed due to version control
4059 d->filename.refresh();
4060 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4062 bool const success = loadLyXFile(d->filename);
4068 message(bformat(_("Document %1$s reloaded."), disp_fn));
4070 message(bformat(_("Could not reload document %1$s."), disp_fn));
4073 thePreviews().removeLoader(*this);
4074 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
4075 thePreviews().generateBufferPreviews(*this);
4081 // FIXME We could do better here, but it is complicated. What would be
4082 // nice is to offer either (a) to save the child buffer to an appropriate
4083 // location, so that it would "move with the master", or else (b) to update
4084 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4085 // complicated, because the code for this lives in GuiView.
4086 void Buffer::checkChildBuffers()
4088 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4089 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4090 for (; it != en; ++it) {
4091 DocIterator dit = it->second;
4092 Buffer * cbuf = const_cast<Buffer *>(it->first);
4093 if (!cbuf || !theBufferList().isLoaded(cbuf))
4095 Inset * inset = dit.nextInset();
4096 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4097 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4098 docstring const & incfile = inset_inc->getParam("filename");
4099 string oldloc = cbuf->absFileName();
4100 string newloc = makeAbsPath(to_utf8(incfile),
4101 onlyPath(absFileName())).absFileName();
4102 if (oldloc == newloc)
4104 // the location of the child file is incorrect.
4105 Alert::warning(_("Included File Invalid"),
4106 bformat(_("Saving this document to a new location has made the file:\n"
4108 "inaccessible. You will need to update the included filename."),
4109 from_utf8(oldloc)));
4111 inset_inc->setChildBuffer(0);
4113 // invalidate cache of children
4114 d->children_positions.clear();
4115 d->position_to_children.clear();