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 "DocIterator.h"
29 #include "ErrorList.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
36 #include "LaTeXFeatures.h"
40 #include "LyXAction.h"
44 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
55 #include "TexStream.h"
57 #include "TextClass.h"
58 #include "TocBackend.h"
60 #include "VCBackend.h"
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
77 #include "graphics/Previews.h"
79 #include "support/lassert.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
97 #include <boost/bind.hpp>
109 using namespace std::tr1;
110 using namespace lyx::support;
114 namespace Alert = frontend::Alert;
115 namespace os = support::os;
119 // Do not remove the comment below, so we get merge conflict in
120 // independent branches. Instead add your own.
121 int const LYX_FORMAT = 345; // jamatos: xml elements
123 typedef map<string, bool> DepClean;
124 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
131 Impl(Buffer & parent, FileName const & file, bool readonly);
145 mutable TexRow texrow;
146 Buffer const * parent_buffer;
148 /// need to regenerate .tex?
152 mutable bool lyx_clean;
154 /// is autosave needed?
155 mutable bool bak_clean;
157 /// is this a unnamed file (New...)?
163 /// name of the file the buffer is associated with.
166 /** Set to true only when the file is fully loaded.
167 * Used to prevent the premature generation of previews
168 * and by the citation inset.
170 bool file_fully_loaded;
173 mutable TocBackend toc_backend;
176 typedef pair<DocIterator, MacroData> ScopeMacro;
177 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
178 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
179 /// map from the macro name to the position map,
180 /// which maps the macro definition position to the scope and the MacroData.
181 NamePositionScopeMacroMap macros;
184 /// positions of child buffers in the buffer
185 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
186 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
187 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
188 /// position of children buffers in this buffer
189 BufferPositionMap children_positions;
190 /// map from children inclusion positions to their scope and their buffer
191 PositionScopeBufferMap position_to_children;
193 /// Container for all sort of Buffer dependant errors.
194 map<string, ErrorList> errorLists;
196 /// timestamp and checksum used to test if the file has been externally
197 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
199 unsigned long checksum_;
202 frontend::WorkAreaManager * wa_;
207 /// A cache for the bibfiles (including bibfiles of loaded child
208 /// documents), needed for appropriate update of natbib labels.
209 mutable support::FileNameList bibfilesCache_;
211 // FIXME The caching mechanism could be improved. At present, we have a
212 // cache for each Buffer, that caches all the bibliography info for that
213 // Buffer. A more efficient solution would be to have a global cache per
214 // file, and then to construct the Buffer's bibinfo from that.
215 /// A cache for bibliography info
216 mutable BiblioInfo bibinfo_;
217 /// whether the bibinfo cache is valid
218 bool bibinfoCacheValid_;
219 /// Cache of timestamps of .bib files
220 map<FileName, time_t> bibfileStatus_;
222 mutable RefCache ref_cache_;
224 /// our Text that should be wrapped in an InsetText
229 /// Creates the per buffer temporary directory
230 static FileName createBufferTmpDir()
233 // We are in our own directory. Why bother to mangle name?
234 // In fact I wrote this code to circumvent a problematic behaviour
235 // (bug?) of EMX mkstemp().
236 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
237 convert<string>(count++));
239 if (!tmpfl.createDirectory(0777)) {
240 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
241 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
242 from_utf8(tmpfl.absFilename())));
248 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
249 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
250 read_only(readonly_), filename(file), file_fully_loaded(false),
251 toc_backend(&parent), macro_lock(false), timestamp_(0),
252 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false)
254 temppath = createBufferTmpDir();
255 lyxvc.setBuffer(&parent);
257 wa_ = new frontend::WorkAreaManager;
261 Buffer::Buffer(string const & file, bool readonly)
262 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
264 LYXERR(Debug::INFO, "Buffer::Buffer()");
266 d->inset = new InsetText(*this);
267 d->inset->setAutoBreakRows(true);
268 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
274 LYXERR(Debug::INFO, "Buffer::~Buffer()");
275 // here the buffer should take care that it is
276 // saved properly, before it goes into the void.
278 // GuiView already destroyed
281 if (d->unnamed && d->filename.extension() == "internal") {
282 // No need to do additional cleanups for internal buffer.
287 // loop over children
288 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
289 Impl::BufferPositionMap::iterator end = d->children_positions.end();
290 for (; it != end; ++it)
291 theBufferList().releaseChild(this, const_cast<Buffer *>(it->first));
293 // clear references to children in macro tables
294 d->children_positions.clear();
295 d->position_to_children.clear();
297 if (!d->temppath.destroyDirectory()) {
298 Alert::warning(_("Could not remove temporary directory"),
299 bformat(_("Could not remove the temporary directory %1$s"),
300 from_utf8(d->temppath.absFilename())));
303 // Remove any previewed LaTeX snippets associated with this buffer.
304 thePreviews().removeLoader(*this);
310 void Buffer::changed() const
317 frontend::WorkAreaManager & Buffer::workAreaManager() const
319 LASSERT(d->wa_, /**/);
324 Text & Buffer::text() const
326 return d->inset->text();
330 Inset & Buffer::inset() const
336 BufferParams & Buffer::params()
342 BufferParams const & Buffer::params() const
348 ParagraphList & Buffer::paragraphs()
350 return text().paragraphs();
354 ParagraphList const & Buffer::paragraphs() const
356 return text().paragraphs();
360 LyXVC & Buffer::lyxvc()
366 LyXVC const & Buffer::lyxvc() const
372 string const Buffer::temppath() const
374 return d->temppath.absFilename();
378 TexRow & Buffer::texrow()
384 TexRow const & Buffer::texrow() const
390 TocBackend & Buffer::tocBackend() const
392 return d->toc_backend;
396 Undo & Buffer::undo()
402 string Buffer::latexName(bool const no_path) const
404 FileName latex_name = makeLatexName(d->filename);
405 return no_path ? latex_name.onlyFileName()
406 : latex_name.absFilename();
410 string Buffer::logName(LogType * type) const
412 string const filename = latexName(false);
414 if (filename.empty()) {
420 string const path = temppath();
422 FileName const fname(addName(temppath(),
423 onlyFilename(changeExtension(filename,
425 FileName const bname(
426 addName(path, onlyFilename(
427 changeExtension(filename,
428 formats.extension("literate") + ".out"))));
430 // If no Latex log or Build log is newer, show Build log
432 if (bname.exists() &&
433 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
434 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
437 return bname.absFilename();
439 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
442 return fname.absFilename();
446 void Buffer::setReadonly(bool const flag)
448 if (d->read_only != flag) {
455 void Buffer::setFileName(string const & newfile)
457 d->filename = makeAbsPath(newfile);
458 setReadonly(d->filename.isReadOnly());
463 int Buffer::readHeader(Lexer & lex)
465 int unknown_tokens = 0;
467 int begin_header_line = -1;
469 // Initialize parameters that may be/go lacking in header:
470 params().branchlist().clear();
471 params().preamble.erase();
472 params().options.erase();
473 params().master.erase();
474 params().float_placement.erase();
475 params().paperwidth.erase();
476 params().paperheight.erase();
477 params().leftmargin.erase();
478 params().rightmargin.erase();
479 params().topmargin.erase();
480 params().bottommargin.erase();
481 params().headheight.erase();
482 params().headsep.erase();
483 params().footskip.erase();
484 params().columnsep.erase();
485 params().fontsCJK.erase();
486 params().listings_params.clear();
487 params().clearLayoutModules();
488 params().clearRemovedModules();
489 params().pdfoptions().clear();
491 for (int i = 0; i < 4; ++i) {
492 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
493 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
496 ErrorList & errorList = d->errorLists["Parse"];
505 if (token == "\\end_header")
509 if (token == "\\begin_header") {
510 begin_header_line = line;
514 LYXERR(Debug::PARSER, "Handling document header token: `"
517 string unknown = params().readToken(lex, token, d->filename.onlyPath());
518 if (!unknown.empty()) {
519 if (unknown[0] != '\\' && token == "\\textclass") {
520 Alert::warning(_("Unknown document class"),
521 bformat(_("Using the default document class, because the "
522 "class %1$s is unknown."), from_utf8(unknown)));
525 docstring const s = bformat(_("Unknown token: "
529 errorList.push_back(ErrorItem(_("Document header error"),
534 if (begin_header_line) {
535 docstring const s = _("\\begin_header is missing");
536 errorList.push_back(ErrorItem(_("Document header error"),
540 params().makeDocumentClass();
542 return unknown_tokens;
547 // changed to be public and have one parameter
548 // Returns false if "\end_document" is not read (Asger)
549 bool Buffer::readDocument(Lexer & lex)
551 ErrorList & errorList = d->errorLists["Parse"];
554 if (!lex.checkFor("\\begin_document")) {
555 docstring const s = _("\\begin_document is missing");
556 errorList.push_back(ErrorItem(_("Document header error"),
560 // we are reading in a brand new document
561 LASSERT(paragraphs().empty(), /**/);
565 if (params().outputChanges) {
566 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
567 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
568 LaTeXFeatures::isAvailable("xcolor");
570 if (!dvipost && !xcolorsoul) {
571 Alert::warning(_("Changes not shown in LaTeX output"),
572 _("Changes will not be highlighted in LaTeX output, "
573 "because neither dvipost nor xcolor/soul are installed.\n"
574 "Please install these packages or redefine "
575 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
576 } else if (!xcolorsoul) {
577 Alert::warning(_("Changes not shown in LaTeX output"),
578 _("Changes will not be highlighted in LaTeX output "
579 "when using pdflatex, because xcolor and soul are not installed.\n"
580 "Please install both packages or redefine "
581 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
585 if (!params().master.empty()) {
586 FileName const master_file = makeAbsPath(params().master,
587 onlyPath(absFileName()));
588 if (isLyXFilename(master_file.absFilename())) {
589 Buffer * master = checkAndLoadLyXFile(master_file);
590 d->parent_buffer = master;
595 bool const res = text().read(*this, lex, errorList, d->inset);
598 updateMacroInstances();
603 // needed to insert the selection
604 void Buffer::insertStringAsLines(ParagraphList & pars,
605 pit_type & pit, pos_type & pos,
606 Font const & fn, docstring const & str, bool autobreakrows)
610 // insert the string, don't insert doublespace
611 bool space_inserted = true;
612 for (docstring::const_iterator cit = str.begin();
613 cit != str.end(); ++cit) {
614 Paragraph & par = pars[pit];
616 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
617 breakParagraph(params(), pars, pit, pos,
618 par.layout().isEnvironment());
621 space_inserted = true;
625 // do not insert consecutive spaces if !free_spacing
626 } else if ((*cit == ' ' || *cit == '\t') &&
627 space_inserted && !par.isFreeSpacing()) {
629 } else if (*cit == '\t') {
630 if (!par.isFreeSpacing()) {
631 // tabs are like spaces here
632 par.insertChar(pos, ' ', font, params().trackChanges);
634 space_inserted = true;
636 par.insertChar(pos, *cit, font, params().trackChanges);
638 space_inserted = true;
640 } else if (!isPrintable(*cit)) {
641 // Ignore unprintables
644 // just insert the character
645 par.insertChar(pos, *cit, font, params().trackChanges);
647 space_inserted = (*cit == ' ');
654 bool Buffer::readString(string const & s)
656 params().compressed = false;
658 // remove dummy empty par
659 paragraphs().clear();
663 FileName const name = FileName::tempName("Buffer_readString");
664 switch (readFile(lex, name, true)) {
668 // We need to call lyx2lyx, so write the input to a file
669 ofstream os(name.toFilesystemEncoding().c_str());
672 return readFile(name);
682 bool Buffer::readFile(FileName const & filename)
684 FileName fname(filename);
686 // remove dummy empty par
687 paragraphs().clear();
690 if (readFile(lex, fname) != success)
697 bool Buffer::isFullyLoaded() const
699 return d->file_fully_loaded;
703 void Buffer::setFullyLoaded(bool value)
705 d->file_fully_loaded = value;
709 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
712 LASSERT(!filename.empty(), /**/);
714 // the first (non-comment) token _must_ be...
715 if (!lex.checkFor("\\lyxformat")) {
716 Alert::error(_("Document format failure"),
717 bformat(_("%1$s is not a readable LyX document."),
718 from_utf8(filename.absFilename())));
724 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
725 // if present remove ".," from string.
726 size_t dot = tmp_format.find_first_of(".,");
727 //lyxerr << " dot found at " << dot << endl;
728 if (dot != string::npos)
729 tmp_format.erase(dot, 1);
730 int const file_format = convert<int>(tmp_format);
731 //lyxerr << "format: " << file_format << endl;
733 // save timestamp and checksum of the original disk file, making sure
734 // to not overwrite them with those of the file created in the tempdir
735 // when it has to be converted to the current format.
737 // Save the timestamp and checksum of disk file. If filename is an
738 // emergency file, save the timestamp and checksum of the original lyx file
739 // because isExternallyModified will check for this file. (BUG4193)
740 string diskfile = filename.absFilename();
741 if (suffixIs(diskfile, ".emergency"))
742 diskfile = diskfile.substr(0, diskfile.size() - 10);
743 saveCheckSum(FileName(diskfile));
746 if (file_format != LYX_FORMAT) {
749 // lyx2lyx would fail
752 FileName const tmpfile = FileName::tempName("Buffer_readFile");
753 if (tmpfile.empty()) {
754 Alert::error(_("Conversion failed"),
755 bformat(_("%1$s is from a different"
756 " version of LyX, but a temporary"
757 " file for converting it could"
759 from_utf8(filename.absFilename())));
762 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
763 if (lyx2lyx.empty()) {
764 Alert::error(_("Conversion script not found"),
765 bformat(_("%1$s is from a different"
766 " version of LyX, but the"
767 " conversion script lyx2lyx"
768 " could not be found."),
769 from_utf8(filename.absFilename())));
772 ostringstream command;
773 command << os::python()
774 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
775 << " -t " << convert<string>(LYX_FORMAT)
776 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
777 << ' ' << quoteName(filename.toFilesystemEncoding());
778 string const command_str = command.str();
780 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
782 cmd_ret const ret = runCommand(command_str);
783 if (ret.first != 0) {
784 Alert::error(_("Conversion script failed"),
785 bformat(_("%1$s is from a different version"
786 " of LyX, but the lyx2lyx script"
787 " failed to convert it."),
788 from_utf8(filename.absFilename())));
791 bool const ret = readFile(tmpfile);
792 // Do stuff with tmpfile name and buffer name here.
793 return ret ? success : failure;
798 if (readDocument(lex)) {
799 Alert::error(_("Document format failure"),
800 bformat(_("%1$s ended unexpectedly, which means"
801 " that it is probably corrupted."),
802 from_utf8(filename.absFilename())));
805 d->file_fully_loaded = true;
810 // Should probably be moved to somewhere else: BufferView? LyXView?
811 bool Buffer::save() const
813 // We don't need autosaves in the immediate future. (Asger)
814 resetAutosaveTimers();
816 string const encodedFilename = d->filename.toFilesystemEncoding();
819 bool madeBackup = false;
821 // make a backup if the file already exists
822 if (lyxrc.make_backup && fileName().exists()) {
823 backupName = FileName(absFileName() + '~');
824 if (!lyxrc.backupdir_path.empty()) {
825 string const mangledName =
826 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
827 backupName = FileName(addName(lyxrc.backupdir_path,
830 if (fileName().copyTo(backupName)) {
833 Alert::error(_("Backup failure"),
834 bformat(_("Cannot create backup file %1$s.\n"
835 "Please check whether the directory exists and is writeable."),
836 from_utf8(backupName.absFilename())));
837 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
841 // ask if the disk file has been externally modified (use checksum method)
842 if (fileName().exists() && isExternallyModified(checksum_method)) {
843 docstring const file = makeDisplayPath(absFileName(), 20);
844 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
845 "you want to overwrite this file?"), file);
846 int const ret = Alert::prompt(_("Overwrite modified file?"),
847 text, 1, 1, _("&Overwrite"), _("&Cancel"));
852 if (writeFile(d->filename)) {
856 // Saving failed, so backup is not backup
858 backupName.moveTo(d->filename);
864 bool Buffer::writeFile(FileName const & fname) const
866 if (d->read_only && fname == d->filename)
871 docstring const str = bformat(_("Saving document %1$s..."),
872 makeDisplayPath(fname.absFilename()));
875 if (params().compressed) {
876 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
877 retval = ofs && write(ofs);
879 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
880 retval = ofs && write(ofs);
884 message(str + _(" could not write file!"));
888 removeAutosaveFile(d->filename.absFilename());
890 saveCheckSum(d->filename);
891 message(str + _(" done."));
897 bool Buffer::write(ostream & ofs) const
900 // Use the standard "C" locale for file output.
901 ofs.imbue(locale::classic());
904 // The top of the file should not be written by params().
906 // write out a comment in the top of the file
907 ofs << "#LyX " << lyx_version
908 << " created this file. For more info see http://www.lyx.org/\n"
909 << "\\lyxformat " << LYX_FORMAT << "\n"
910 << "\\begin_document\n";
912 /// For each author, set 'used' to true if there is a change
913 /// by this author in the document; otherwise set it to 'false'.
914 AuthorList::Authors::const_iterator a_it = params().authors().begin();
915 AuthorList::Authors::const_iterator a_end = params().authors().end();
916 for (; a_it != a_end; ++a_it)
917 a_it->second.setUsed(false);
919 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
920 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
921 for ( ; it != end; ++it)
922 it->checkAuthors(params().authors());
924 // now write out the buffer parameters.
925 ofs << "\\begin_header\n";
926 params().writeFile(ofs);
927 ofs << "\\end_header\n";
930 ofs << "\n\\begin_body\n";
931 text().write(*this, ofs);
932 ofs << "\n\\end_body\n";
934 // Write marker that shows file is complete
935 ofs << "\\end_document" << endl;
937 // Shouldn't really be needed....
940 // how to check if close went ok?
941 // Following is an attempt... (BE 20001011)
943 // good() returns false if any error occured, including some
945 // bad() returns true if something bad happened in the buffer,
946 // which should include file system full errors.
951 lyxerr << "File was not closed properly." << endl;
958 bool Buffer::makeLaTeXFile(FileName const & fname,
959 string const & original_path,
960 OutputParams const & runparams,
961 bool output_preamble, bool output_body) const
963 string const encoding = runparams.encoding->iconvName();
964 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
967 try { ofs.reset(encoding); }
968 catch (iconv_codecvt_facet_exception & e) {
969 lyxerr << "Caught iconv exception: " << e.what() << endl;
970 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
971 "verify that the support software for your encoding (%1$s) is "
972 "properly installed"), from_ascii(encoding)));
975 if (!openFileWrite(ofs, fname))
978 //TexStream ts(ofs.rdbuf(), &texrow());
979 ErrorList & errorList = d->errorLists["Export"];
981 bool failed_export = false;
984 writeLaTeXSource(ofs, original_path,
985 runparams, output_preamble, output_body);
987 catch (EncodingException & e) {
988 odocstringstream ods;
989 ods.put(e.failed_char);
991 oss << "0x" << hex << e.failed_char << dec;
992 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
993 " (code point %2$s)"),
994 ods.str(), from_utf8(oss.str()));
995 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
996 "representable in the chosen encoding.\n"
997 "Changing the document encoding to utf8 could help."),
998 e.par_id, e.pos, e.pos + 1));
999 failed_export = true;
1001 catch (iconv_codecvt_facet_exception & e) {
1002 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1003 _(e.what()), -1, 0, 0));
1004 failed_export = true;
1006 catch (exception const & e) {
1007 errorList.push_back(ErrorItem(_("conversion failed"),
1008 _(e.what()), -1, 0, 0));
1009 failed_export = true;
1012 lyxerr << "Caught some really weird exception..." << endl;
1018 failed_export = true;
1019 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1023 return !failed_export;
1027 void Buffer::writeLaTeXSource(odocstream & os,
1028 string const & original_path,
1029 OutputParams const & runparams_in,
1030 bool const output_preamble, bool const output_body) const
1032 // The child documents, if any, shall be already loaded at this point.
1034 OutputParams runparams = runparams_in;
1036 // Classify the unicode characters appearing in math insets
1037 Encodings::initUnicodeMath(*this);
1039 // validate the buffer.
1040 LYXERR(Debug::LATEX, " Validating buffer...");
1041 LaTeXFeatures features(*this, params(), runparams);
1043 LYXERR(Debug::LATEX, " Buffer validation done.");
1045 // The starting paragraph of the coming rows is the
1046 // first paragraph of the document. (Asger)
1047 if (output_preamble && runparams.nice) {
1048 os << "%% LyX " << lyx_version << " created this file. "
1049 "For more info, see http://www.lyx.org/.\n"
1050 "%% Do not edit unless you really know what "
1052 d->texrow.newline();
1053 d->texrow.newline();
1055 LYXERR(Debug::INFO, "lyx document header finished");
1057 // Don't move this behind the parent_buffer=0 code below,
1058 // because then the macros will not get the right "redefinition"
1059 // flag as they don't see the parent macros which are output before.
1062 // fold macros if possible, still with parent buffer as the
1063 // macros will be put in the prefix anyway.
1064 updateMacroInstances();
1066 // There are a few differences between nice LaTeX and usual files:
1067 // usual is \batchmode and has a
1068 // special input@path to allow the including of figures
1069 // with either \input or \includegraphics (what figinsets do).
1070 // input@path is set when the actual parameter
1071 // original_path is set. This is done for usual tex-file, but not
1072 // for nice-latex-file. (Matthias 250696)
1073 // Note that input@path is only needed for something the user does
1074 // in the preamble, included .tex files or ERT, files included by
1075 // LyX work without it.
1076 if (output_preamble) {
1077 if (!runparams.nice) {
1078 // code for usual, NOT nice-latex-file
1079 os << "\\batchmode\n"; // changed
1080 // from \nonstopmode
1081 d->texrow.newline();
1083 if (!original_path.empty()) {
1085 // We don't know the encoding of inputpath
1086 docstring const inputpath = from_utf8(latex_path(original_path));
1087 os << "\\makeatletter\n"
1088 << "\\def\\input@path{{"
1089 << inputpath << "/}}\n"
1090 << "\\makeatother\n";
1091 d->texrow.newline();
1092 d->texrow.newline();
1093 d->texrow.newline();
1096 // get parent macros (if this buffer has a parent) which will be
1097 // written at the document begin further down.
1098 MacroSet parentMacros;
1099 listParentMacros(parentMacros, features);
1101 // Write the preamble
1102 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1104 runparams.use_japanese = features.isRequired("japanese");
1110 os << "\\begin{document}\n";
1111 d->texrow.newline();
1113 // output the parent macros
1114 MacroSet::iterator it = parentMacros.begin();
1115 MacroSet::iterator end = parentMacros.end();
1116 for (; it != end; ++it)
1117 (*it)->write(os, true);
1118 } // output_preamble
1120 d->texrow.start(paragraphs().begin()->id(), 0);
1122 LYXERR(Debug::INFO, "preamble finished, now the body.");
1124 // if we are doing a real file with body, even if this is the
1125 // child of some other buffer, let's cut the link here.
1126 // This happens for example if only a child document is printed.
1127 Buffer const * save_parent = 0;
1128 if (output_preamble) {
1129 save_parent = d->parent_buffer;
1130 d->parent_buffer = 0;
1134 latexParagraphs(*this, text(), os, d->texrow, runparams);
1136 // Restore the parenthood if needed
1137 if (output_preamble)
1138 d->parent_buffer = save_parent;
1140 // add this just in case after all the paragraphs
1142 d->texrow.newline();
1144 if (output_preamble) {
1145 os << "\\end{document}\n";
1146 d->texrow.newline();
1147 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1149 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1151 runparams_in.encoding = runparams.encoding;
1153 // Just to be sure. (Asger)
1154 d->texrow.newline();
1156 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1157 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1161 bool Buffer::isLatex() const
1163 return params().documentClass().outputType() == LATEX;
1167 bool Buffer::isLiterate() const
1169 return params().documentClass().outputType() == LITERATE;
1173 bool Buffer::isDocBook() const
1175 return params().documentClass().outputType() == DOCBOOK;
1179 void Buffer::makeDocBookFile(FileName const & fname,
1180 OutputParams const & runparams,
1181 bool const body_only) const
1183 LYXERR(Debug::LATEX, "makeDocBookFile...");
1186 if (!openFileWrite(ofs, fname))
1189 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1193 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1197 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1198 OutputParams const & runparams,
1199 bool const only_body) const
1201 LaTeXFeatures features(*this, params(), runparams);
1206 DocumentClass const & tclass = params().documentClass();
1207 string const top_element = tclass.latexname();
1210 if (runparams.flavor == OutputParams::XML)
1211 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1214 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1217 if (! tclass.class_header().empty())
1218 os << from_ascii(tclass.class_header());
1219 else if (runparams.flavor == OutputParams::XML)
1220 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1221 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1223 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1225 docstring preamble = from_utf8(params().preamble);
1226 if (runparams.flavor != OutputParams::XML ) {
1227 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1228 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1229 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1230 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1233 string const name = runparams.nice
1234 ? changeExtension(absFileName(), ".sgml") : fname;
1235 preamble += features.getIncludedFiles(name);
1236 preamble += features.getLyXSGMLEntities();
1238 if (!preamble.empty()) {
1239 os << "\n [ " << preamble << " ]";
1244 string top = top_element;
1246 if (runparams.flavor == OutputParams::XML)
1247 top += params().language->code();
1249 top += params().language->code().substr(0, 2);
1252 if (!params().options.empty()) {
1254 top += params().options;
1257 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1258 << " file was created by LyX " << lyx_version
1259 << "\n See http://www.lyx.org/ for more information -->\n";
1261 params().documentClass().counters().reset();
1265 sgml::openTag(os, top);
1267 docbookParagraphs(paragraphs(), *this, os, runparams);
1268 sgml::closeTag(os, top_element);
1272 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1273 // Other flags: -wall -v0 -x
1274 int Buffer::runChktex()
1278 // get LaTeX-Filename
1279 FileName const path(temppath());
1280 string const name = addName(path.absFilename(), latexName());
1281 string const org_path = filePath();
1283 PathChanger p(path); // path to LaTeX file
1284 message(_("Running chktex..."));
1286 // Generate the LaTeX file if neccessary
1287 OutputParams runparams(¶ms().encoding());
1288 runparams.flavor = OutputParams::LATEX;
1289 runparams.nice = false;
1290 makeLaTeXFile(FileName(name), org_path, runparams);
1293 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1294 int const res = chktex.run(terr); // run chktex
1297 Alert::error(_("chktex failure"),
1298 _("Could not run chktex successfully."));
1299 } else if (res > 0) {
1300 ErrorList & errlist = d->errorLists["ChkTeX"];
1302 bufferErrors(terr, errlist);
1313 void Buffer::validate(LaTeXFeatures & features) const
1315 params().validate(features);
1319 for_each(paragraphs().begin(), paragraphs().end(),
1320 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1322 if (lyxerr.debugging(Debug::LATEX)) {
1323 features.showStruct();
1328 void Buffer::getLabelList(vector<docstring> & list) const
1330 // If this is a child document, use the parent's list instead.
1331 if (d->parent_buffer) {
1332 d->parent_buffer->getLabelList(list);
1337 Toc & toc = d->toc_backend.toc("label");
1338 TocIterator toc_it = toc.begin();
1339 TocIterator end = toc.end();
1340 for (; toc_it != end; ++toc_it) {
1341 if (toc_it->depth() == 0)
1342 list.push_back(toc_it->str());
1347 void Buffer::updateBibfilesCache() const
1349 // If this is a child document, use the parent's cache instead.
1350 if (d->parent_buffer) {
1351 d->parent_buffer->updateBibfilesCache();
1355 d->bibfilesCache_.clear();
1356 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1357 if (it->lyxCode() == BIBTEX_CODE) {
1358 InsetBibtex const & inset =
1359 static_cast<InsetBibtex const &>(*it);
1360 support::FileNameList const bibfiles = inset.getBibFiles();
1361 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1364 } else if (it->lyxCode() == INCLUDE_CODE) {
1365 InsetInclude & inset =
1366 static_cast<InsetInclude &>(*it);
1367 inset.updateBibfilesCache();
1368 support::FileNameList const & bibfiles =
1369 inset.getBibfilesCache(*this);
1370 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1375 // the bibinfo cache is now invalid
1376 d->bibinfoCacheValid_ = false;
1380 void Buffer::invalidateBibinfoCache()
1382 d->bibinfoCacheValid_ = false;
1386 support::FileNameList const & Buffer::getBibfilesCache() const
1388 // If this is a child document, use the parent's cache instead.
1389 if (d->parent_buffer)
1390 return d->parent_buffer->getBibfilesCache();
1392 // We update the cache when first used instead of at loading time.
1393 if (d->bibfilesCache_.empty())
1394 const_cast<Buffer *>(this)->updateBibfilesCache();
1396 return d->bibfilesCache_;
1400 BiblioInfo const & Buffer::masterBibInfo() const
1402 // if this is a child document and the parent is already loaded
1403 // use the parent's list instead [ale990412]
1404 Buffer const * const tmp = masterBuffer();
1407 return tmp->masterBibInfo();
1408 return localBibInfo();
1412 BiblioInfo const & Buffer::localBibInfo() const
1414 if (d->bibinfoCacheValid_) {
1415 support::FileNameList const & bibfilesCache = getBibfilesCache();
1416 // compare the cached timestamps with the actual ones.
1417 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1418 support::FileNameList::const_iterator en = bibfilesCache.end();
1419 for (; ei != en; ++ ei) {
1420 time_t lastw = ei->lastModified();
1421 if (lastw != d->bibfileStatus_[*ei]) {
1422 d->bibinfoCacheValid_ = false;
1423 d->bibfileStatus_[*ei] = lastw;
1429 if (!d->bibinfoCacheValid_) {
1430 d->bibinfo_.clear();
1431 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1432 it->fillWithBibKeys(d->bibinfo_, it);
1433 d->bibinfoCacheValid_ = true;
1439 bool Buffer::isDepClean(string const & name) const
1441 DepClean::const_iterator const it = d->dep_clean.find(name);
1442 if (it == d->dep_clean.end())
1448 void Buffer::markDepClean(string const & name)
1450 d->dep_clean[name] = true;
1454 bool Buffer::dispatch(string const & command, bool * result)
1456 return dispatch(lyxaction.lookupFunc(command), result);
1460 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1462 bool dispatched = true;
1464 switch (func.action) {
1465 case LFUN_BUFFER_EXPORT: {
1466 bool const tmp = doExport(to_utf8(func.argument()), false);
1472 case LFUN_BRANCH_ACTIVATE:
1473 case LFUN_BRANCH_DEACTIVATE: {
1474 BranchList & branchList = params().branchlist();
1475 docstring const branchName = func.argument();
1476 Branch * branch = branchList.find(branchName);
1478 LYXERR0("Branch " << branchName << " does not exist.");
1480 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1492 void Buffer::changeLanguage(Language const * from, Language const * to)
1494 LASSERT(from, /**/);
1497 for_each(par_iterator_begin(),
1499 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1503 bool Buffer::isMultiLingual() const
1505 ParConstIterator end = par_iterator_end();
1506 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1507 if (it->isMultiLingual(params()))
1514 DocIterator Buffer::getParFromID(int const id) const
1517 // John says this is called with id == -1 from undo
1518 lyxerr << "getParFromID(), id: " << id << endl;
1519 return doc_iterator_end(inset());
1522 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1523 if (it.paragraph().id() == id)
1526 return doc_iterator_end(inset());
1530 bool Buffer::hasParWithID(int const id) const
1532 return !getParFromID(id).atEnd();
1536 ParIterator Buffer::par_iterator_begin()
1538 return ParIterator(doc_iterator_begin(inset()));
1542 ParIterator Buffer::par_iterator_end()
1544 return ParIterator(doc_iterator_end(inset()));
1548 ParConstIterator Buffer::par_iterator_begin() const
1550 return lyx::par_const_iterator_begin(inset());
1554 ParConstIterator Buffer::par_iterator_end() const
1556 return lyx::par_const_iterator_end(inset());
1560 Language const * Buffer::language() const
1562 return params().language;
1566 docstring const Buffer::B_(string const & l10n) const
1568 return params().B_(l10n);
1572 bool Buffer::isClean() const
1574 return d->lyx_clean;
1578 bool Buffer::isBakClean() const
1580 return d->bak_clean;
1584 bool Buffer::isExternallyModified(CheckMethod method) const
1586 LASSERT(d->filename.exists(), /**/);
1587 // if method == timestamp, check timestamp before checksum
1588 return (method == checksum_method
1589 || d->timestamp_ != d->filename.lastModified())
1590 && d->checksum_ != d->filename.checksum();
1594 void Buffer::saveCheckSum(FileName const & file) const
1596 if (file.exists()) {
1597 d->timestamp_ = file.lastModified();
1598 d->checksum_ = file.checksum();
1600 // in the case of save to a new file.
1607 void Buffer::markClean() const
1609 if (!d->lyx_clean) {
1610 d->lyx_clean = true;
1613 // if the .lyx file has been saved, we don't need an
1615 d->bak_clean = true;
1619 void Buffer::markBakClean() const
1621 d->bak_clean = true;
1625 void Buffer::setUnnamed(bool flag)
1631 bool Buffer::isUnnamed() const
1637 // FIXME: this function should be moved to buffer_pimpl.C
1638 void Buffer::markDirty()
1641 d->lyx_clean = false;
1644 d->bak_clean = false;
1646 DepClean::iterator it = d->dep_clean.begin();
1647 DepClean::const_iterator const end = d->dep_clean.end();
1649 for (; it != end; ++it)
1654 FileName Buffer::fileName() const
1660 string Buffer::absFileName() const
1662 return d->filename.absFilename();
1666 string Buffer::filePath() const
1668 return d->filename.onlyPath().absFilename() + "/";
1672 bool Buffer::isReadonly() const
1674 return d->read_only;
1678 void Buffer::setParent(Buffer const * buffer)
1680 // Avoids recursive include.
1681 d->parent_buffer = buffer == this ? 0 : buffer;
1686 Buffer const * Buffer::parent()
1688 return d->parent_buffer;
1692 Buffer const * Buffer::masterBuffer() const
1694 if (!d->parent_buffer)
1697 return d->parent_buffer->masterBuffer();
1701 bool Buffer::isChild(Buffer * child) const
1703 return d->children_positions.find(child) != d->children_positions.end();
1707 template<typename M>
1708 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1713 typename M::iterator it = m.lower_bound(x);
1714 if (it == m.begin())
1722 MacroData const * Buffer::getBufferMacro(docstring const & name,
1723 DocIterator const & pos) const
1725 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1727 // if paragraphs have no macro context set, pos will be empty
1731 // we haven't found anything yet
1732 DocIterator bestPos = par_iterator_begin();
1733 MacroData const * bestData = 0;
1735 // find macro definitions for name
1736 Impl::NamePositionScopeMacroMap::iterator nameIt
1737 = d->macros.find(name);
1738 if (nameIt != d->macros.end()) {
1739 // find last definition in front of pos or at pos itself
1740 Impl::PositionScopeMacroMap::const_iterator it
1741 = greatest_below(nameIt->second, pos);
1742 if (it != nameIt->second.end()) {
1744 // scope ends behind pos?
1745 if (pos < it->second.first) {
1746 // Looks good, remember this. If there
1747 // is no external macro behind this,
1748 // we found the right one already.
1749 bestPos = it->first;
1750 bestData = &it->second.second;
1754 // try previous macro if there is one
1755 if (it == nameIt->second.begin())
1762 // find macros in included files
1763 Impl::PositionScopeBufferMap::const_iterator it
1764 = greatest_below(d->position_to_children, pos);
1765 if (it == d->position_to_children.end())
1766 // no children before
1770 // do we know something better (i.e. later) already?
1771 if (it->first < bestPos )
1774 // scope ends behind pos?
1775 if (pos < it->second.first) {
1776 // look for macro in external file
1777 d->macro_lock = true;
1778 MacroData const * data
1779 = it->second.second->getMacro(name, false);
1780 d->macro_lock = false;
1782 bestPos = it->first;
1788 // try previous file if there is one
1789 if (it == d->position_to_children.begin())
1794 // return the best macro we have found
1799 MacroData const * Buffer::getMacro(docstring const & name,
1800 DocIterator const & pos, bool global) const
1805 // query buffer macros
1806 MacroData const * data = getBufferMacro(name, pos);
1810 // If there is a master buffer, query that
1811 if (d->parent_buffer) {
1812 d->macro_lock = true;
1813 MacroData const * macro = d->parent_buffer->getMacro(
1814 name, *this, false);
1815 d->macro_lock = false;
1821 data = MacroTable::globalMacros().get(name);
1830 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1832 // set scope end behind the last paragraph
1833 DocIterator scope = par_iterator_begin();
1834 scope.pit() = scope.lastpit() + 1;
1836 return getMacro(name, scope, global);
1840 MacroData const * Buffer::getMacro(docstring const & name,
1841 Buffer const & child, bool global) const
1843 // look where the child buffer is included first
1844 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1845 if (it == d->children_positions.end())
1848 // check for macros at the inclusion position
1849 return getMacro(name, it->second, global);
1853 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1855 pit_type lastpit = it.lastpit();
1857 // look for macros in each paragraph
1858 while (it.pit() <= lastpit) {
1859 Paragraph & par = it.paragraph();
1861 // iterate over the insets of the current paragraph
1862 InsetList const & insets = par.insetList();
1863 InsetList::const_iterator iit = insets.begin();
1864 InsetList::const_iterator end = insets.end();
1865 for (; iit != end; ++iit) {
1866 it.pos() = iit->pos;
1868 // is it a nested text inset?
1869 if (iit->inset->asInsetText()) {
1870 // Inset needs its own scope?
1871 InsetText const * itext
1872 = iit->inset->asInsetText();
1873 bool newScope = itext->isMacroScope();
1875 // scope which ends just behind the inset
1876 DocIterator insetScope = it;
1879 // collect macros in inset
1880 it.push_back(CursorSlice(*iit->inset));
1881 updateMacros(it, newScope ? insetScope : scope);
1886 // is it an external file?
1887 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1888 // get buffer of external file
1889 InsetCommand const & inset
1890 = static_cast<InsetCommand const &>(*iit->inset);
1891 InsetCommandParams const & ip = inset.params();
1892 d->macro_lock = true;
1893 Buffer * child = loadIfNeeded(*this, ip);
1894 d->macro_lock = false;
1898 // register its position, but only when it is
1899 // included first in the buffer
1900 if (d->children_positions.find(child)
1901 == d->children_positions.end())
1902 d->children_positions[child] = it;
1904 // register child with its scope
1905 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1909 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1913 MathMacroTemplate & macroTemplate
1914 = static_cast<MathMacroTemplate &>(*iit->inset);
1915 MacroContext mc(*this, it);
1916 macroTemplate.updateToContext(mc);
1919 bool valid = macroTemplate.validMacro();
1920 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1921 // then the BufferView's cursor will be invalid in
1922 // some cases which leads to crashes.
1927 d->macros[macroTemplate.name()][it] =
1928 Impl::ScopeMacro(scope, MacroData(*this, it));
1938 void Buffer::updateMacros() const
1943 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1945 // start with empty table
1947 d->children_positions.clear();
1948 d->position_to_children.clear();
1950 // Iterate over buffer, starting with first paragraph
1951 // The scope must be bigger than any lookup DocIterator
1952 // later. For the global lookup, lastpit+1 is used, hence
1953 // we use lastpit+2 here.
1954 DocIterator it = par_iterator_begin();
1955 DocIterator outerScope = it;
1956 outerScope.pit() = outerScope.lastpit() + 2;
1957 updateMacros(it, outerScope);
1961 void Buffer::updateMacroInstances() const
1963 LYXERR(Debug::MACROS, "updateMacroInstances for "
1964 << d->filename.onlyFileName());
1965 DocIterator it = doc_iterator_begin(inset());
1966 DocIterator end = doc_iterator_end(inset());
1967 for (; it != end; it.forwardPos()) {
1968 // look for MathData cells in InsetMathNest insets
1969 Inset * inset = it.nextInset();
1973 InsetMath * minset = inset->asInsetMath();
1977 // update macro in all cells of the InsetMathNest
1978 DocIterator::idx_type n = minset->nargs();
1979 MacroContext mc = MacroContext(*this, it);
1980 for (DocIterator::idx_type i = 0; i < n; ++i) {
1981 MathData & data = minset->cell(i);
1982 data.updateMacros(0, mc);
1988 void Buffer::listMacroNames(MacroNameSet & macros) const
1993 d->macro_lock = true;
1995 // loop over macro names
1996 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1997 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1998 for (; nameIt != nameEnd; ++nameIt)
1999 macros.insert(nameIt->first);
2001 // loop over children
2002 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2003 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2004 for (; it != end; ++it)
2005 it->first->listMacroNames(macros);
2008 if (d->parent_buffer)
2009 d->parent_buffer->listMacroNames(macros);
2011 d->macro_lock = false;
2015 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2017 if (!d->parent_buffer)
2021 d->parent_buffer->listMacroNames(names);
2024 MacroNameSet::iterator it = names.begin();
2025 MacroNameSet::iterator end = names.end();
2026 for (; it != end; ++it) {
2028 MacroData const * data =
2029 d->parent_buffer->getMacro(*it, *this, false);
2031 macros.insert(data);
2033 // we cannot access the original MathMacroTemplate anymore
2034 // here to calls validate method. So we do its work here manually.
2035 // FIXME: somehow make the template accessible here.
2036 if (data->optionals() > 0)
2037 features.require("xargs");
2043 Buffer::References & Buffer::references(docstring const & label)
2045 if (d->parent_buffer)
2046 return const_cast<Buffer *>(masterBuffer())->references(label);
2048 RefCache::iterator it = d->ref_cache_.find(label);
2049 if (it != d->ref_cache_.end())
2050 return it->second.second;
2052 static InsetLabel const * dummy_il = 0;
2053 static References const dummy_refs;
2054 it = d->ref_cache_.insert(
2055 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2056 return it->second.second;
2060 Buffer::References const & Buffer::references(docstring const & label) const
2062 return const_cast<Buffer *>(this)->references(label);
2066 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2068 masterBuffer()->d->ref_cache_[label].first = il;
2072 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2074 return masterBuffer()->d->ref_cache_[label].first;
2078 void Buffer::clearReferenceCache() const
2080 if (!d->parent_buffer)
2081 d->ref_cache_.clear();
2085 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2088 //FIXME: This does not work for child documents yet.
2089 LASSERT(code == CITE_CODE, /**/);
2090 // Check if the label 'from' appears more than once
2091 vector<docstring> labels;
2093 BiblioInfo const & keys = masterBibInfo();
2094 BiblioInfo::const_iterator bit = keys.begin();
2095 BiblioInfo::const_iterator bend = keys.end();
2097 for (; bit != bend; ++bit)
2099 labels.push_back(bit->first);
2102 if (count(labels.begin(), labels.end(), from) > 1)
2105 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2106 if (it->lyxCode() == code) {
2107 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2108 docstring const oldValue = inset.getParam(paramName);
2109 if (oldValue == from)
2110 inset.setParam(paramName, to);
2116 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2117 pit_type par_end, bool full_source) const
2119 OutputParams runparams(¶ms().encoding());
2120 runparams.nice = true;
2121 runparams.flavor = OutputParams::LATEX;
2122 runparams.linelen = lyxrc.plaintext_linelen;
2123 // No side effect of file copying and image conversion
2124 runparams.dryrun = true;
2128 os << "% " << _("Preview source code") << "\n\n";
2129 d->texrow.newline();
2130 d->texrow.newline();
2132 writeDocBookSource(os, absFileName(), runparams, false);
2134 // latex or literate
2135 writeLaTeXSource(os, string(), runparams, true, true);
2137 runparams.par_begin = par_begin;
2138 runparams.par_end = par_end;
2139 if (par_begin + 1 == par_end) {
2141 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2145 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2146 convert<docstring>(par_begin),
2147 convert<docstring>(par_end - 1))
2150 d->texrow.newline();
2151 d->texrow.newline();
2152 // output paragraphs
2154 docbookParagraphs(paragraphs(), *this, os, runparams);
2156 // latex or literate
2157 latexParagraphs(*this, text(), os, d->texrow, runparams);
2162 ErrorList & Buffer::errorList(string const & type) const
2164 static ErrorList emptyErrorList;
2165 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2166 if (I == d->errorLists.end())
2167 return emptyErrorList;
2173 void Buffer::updateTocItem(std::string const & type,
2174 DocIterator const & dit) const
2177 gui_->updateTocItem(type, dit);
2181 void Buffer::structureChanged() const
2184 gui_->structureChanged();
2188 void Buffer::errors(string const & err) const
2195 void Buffer::message(docstring const & msg) const
2202 void Buffer::setBusy(bool on) const
2209 void Buffer::setReadOnly(bool on) const
2212 d->wa_->setReadOnly(on);
2216 void Buffer::updateTitles() const
2219 d->wa_->updateTitles();
2223 void Buffer::resetAutosaveTimers() const
2226 gui_->resetAutosaveTimers();
2230 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2239 class AutoSaveBuffer : public ForkedProcess
2243 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2244 : buffer_(buffer), fname_(fname) {}
2246 virtual boost::shared_ptr<ForkedProcess> clone() const
2248 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2253 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2254 from_utf8(fname_.absFilename())));
2255 return run(DontWait);
2259 virtual int generateChild();
2261 Buffer const & buffer_;
2266 int AutoSaveBuffer::generateChild()
2268 // tmp_ret will be located (usually) in /tmp
2269 // will that be a problem?
2270 // Note that this calls ForkedCalls::fork(), so it's
2271 // ok cross-platform.
2272 pid_t const pid = fork();
2273 // If you want to debug the autosave
2274 // you should set pid to -1, and comment out the fork.
2275 if (pid != 0 && pid != -1)
2278 // pid = -1 signifies that lyx was unable
2279 // to fork. But we will do the save
2281 bool failed = false;
2282 FileName const tmp_ret = FileName::tempName("lyxauto");
2283 if (!tmp_ret.empty()) {
2284 buffer_.writeFile(tmp_ret);
2285 // assume successful write of tmp_ret
2286 if (!tmp_ret.moveTo(fname_))
2292 // failed to write/rename tmp_ret so try writing direct
2293 if (!buffer_.writeFile(fname_)) {
2294 // It is dangerous to do this in the child,
2295 // but safe in the parent, so...
2296 if (pid == -1) // emit message signal.
2297 buffer_.message(_("Autosave failed!"));
2301 if (pid == 0) // we are the child so...
2310 // Perfect target for a thread...
2311 void Buffer::autoSave() const
2313 if (isBakClean() || isReadonly()) {
2314 // We don't save now, but we'll try again later
2315 resetAutosaveTimers();
2319 // emit message signal.
2320 message(_("Autosaving current document..."));
2322 // create autosave filename
2323 string fname = filePath();
2325 fname += d->filename.onlyFileName();
2328 AutoSaveBuffer autosave(*this, FileName(fname));
2332 resetAutosaveTimers();
2336 string Buffer::bufferFormat() const
2342 if (params().encoding().package() == Encoding::japanese)
2348 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2349 string & result_file) const
2351 string backend_format;
2352 OutputParams runparams(¶ms().encoding());
2353 runparams.flavor = OutputParams::LATEX;
2354 runparams.linelen = lyxrc.plaintext_linelen;
2355 vector<string> backs = backends();
2356 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2357 // Get shortest path to format
2358 Graph::EdgePath path;
2359 for (vector<string>::const_iterator it = backs.begin();
2360 it != backs.end(); ++it) {
2361 Graph::EdgePath p = theConverters().getPath(*it, format);
2362 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2363 backend_format = *it;
2368 runparams.flavor = theConverters().getFlavor(path);
2370 Alert::error(_("Couldn't export file"),
2371 bformat(_("No information for exporting the format %1$s."),
2372 formats.prettyName(format)));
2376 backend_format = format;
2377 // FIXME: Don't hardcode format names here, but use a flag
2378 if (backend_format == "pdflatex")
2379 runparams.flavor = OutputParams::PDFLATEX;
2382 string filename = latexName(false);
2383 filename = addName(temppath(), filename);
2384 filename = changeExtension(filename,
2385 formats.extension(backend_format));
2388 updateMacroInstances();
2390 // Plain text backend
2391 if (backend_format == "text")
2392 writePlaintextFile(*this, FileName(filename), runparams);
2394 else if (backend_format == "lyx")
2395 writeFile(FileName(filename));
2397 else if (isDocBook()) {
2398 runparams.nice = !put_in_tempdir;
2399 makeDocBookFile(FileName(filename), runparams);
2402 else if (backend_format == format) {
2403 runparams.nice = true;
2404 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2406 } else if (!lyxrc.tex_allows_spaces
2407 && contains(filePath(), ' ')) {
2408 Alert::error(_("File name error"),
2409 _("The directory path to the document cannot contain spaces."));
2412 runparams.nice = false;
2413 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2417 string const error_type = (format == "program")
2418 ? "Build" : bufferFormat();
2419 ErrorList & error_list = d->errorLists[error_type];
2420 string const ext = formats.extension(format);
2421 FileName const tmp_result_file(changeExtension(filename, ext));
2422 bool const success = theConverters().convert(this, FileName(filename),
2423 tmp_result_file, FileName(absFileName()), backend_format, format,
2425 // Emit the signal to show the error list.
2426 if (format != backend_format)
2431 if (put_in_tempdir) {
2432 result_file = tmp_result_file.absFilename();
2436 result_file = changeExtension(absFileName(), ext);
2437 // We need to copy referenced files (e. g. included graphics
2438 // if format == "dvi") to the result dir.
2439 vector<ExportedFile> const files =
2440 runparams.exportdata->externalFiles(format);
2441 string const dest = onlyPath(result_file);
2442 CopyStatus status = SUCCESS;
2443 for (vector<ExportedFile>::const_iterator it = files.begin();
2444 it != files.end() && status != CANCEL; ++it) {
2445 string const fmt = formats.getFormatFromFile(it->sourceName);
2446 status = copyFile(fmt, it->sourceName,
2447 makeAbsPath(it->exportName, dest),
2448 it->exportName, status == FORCE);
2450 if (status == CANCEL) {
2451 message(_("Document export cancelled."));
2452 } else if (tmp_result_file.exists()) {
2453 // Finally copy the main file
2454 status = copyFile(format, tmp_result_file,
2455 FileName(result_file), result_file,
2457 message(bformat(_("Document exported as %1$s "
2459 formats.prettyName(format),
2460 makeDisplayPath(result_file)));
2462 // This must be a dummy converter like fax (bug 1888)
2463 message(bformat(_("Document exported as %1$s"),
2464 formats.prettyName(format)));
2471 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2474 return doExport(format, put_in_tempdir, result_file);
2478 bool Buffer::preview(string const & format) const
2481 if (!doExport(format, true, result_file))
2483 return formats.view(*this, FileName(result_file), format);
2487 bool Buffer::isExportable(string const & format) const
2489 vector<string> backs = backends();
2490 for (vector<string>::const_iterator it = backs.begin();
2491 it != backs.end(); ++it)
2492 if (theConverters().isReachable(*it, format))
2498 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2500 vector<string> backs = backends();
2501 vector<Format const *> result =
2502 theConverters().getReachable(backs[0], only_viewable, true);
2503 for (vector<string>::const_iterator it = backs.begin() + 1;
2504 it != backs.end(); ++it) {
2505 vector<Format const *> r =
2506 theConverters().getReachable(*it, only_viewable, false);
2507 result.insert(result.end(), r.begin(), r.end());
2513 vector<string> Buffer::backends() const
2516 if (params().baseClass()->isTeXClassAvailable()) {
2517 v.push_back(bufferFormat());
2518 // FIXME: Don't hardcode format names here, but use a flag
2519 if (v.back() == "latex")
2520 v.push_back("pdflatex");
2522 v.push_back("text");
2528 bool Buffer::readFileHelper(FileName const & s)
2530 // File information about normal file
2532 docstring const file = makeDisplayPath(s.absFilename(), 50);
2533 docstring text = bformat(_("The specified document\n%1$s"
2534 "\ncould not be read."), file);
2535 Alert::error(_("Could not read document"), text);
2539 // Check if emergency save file exists and is newer.
2540 FileName const e(s.absFilename() + ".emergency");
2542 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2543 docstring const file = makeDisplayPath(s.absFilename(), 20);
2544 docstring const text =
2545 bformat(_("An emergency save of the document "
2547 "Recover emergency save?"), file);
2548 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2549 _("&Recover"), _("&Load Original"),
2553 // the file is not saved if we load the emergency file.
2563 // Now check if autosave file is newer.
2564 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2566 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2567 docstring const file = makeDisplayPath(s.absFilename(), 20);
2568 docstring const text =
2569 bformat(_("The backup of the document "
2570 "%1$s is newer.\n\nLoad the "
2571 "backup instead?"), file);
2572 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2573 _("&Load backup"), _("Load &original"),
2577 // the file is not saved if we load the autosave file.
2581 // Here we delete the autosave
2592 bool Buffer::loadLyXFile(FileName const & s)
2594 if (s.isReadableFile()) {
2595 if (readFileHelper(s)) {
2596 lyxvc().file_found_hook(s);
2597 if (!s.isWritable())
2602 docstring const file = makeDisplayPath(s.absFilename(), 20);
2603 // Here we probably should run
2604 if (LyXVC::file_not_found_hook(s)) {
2605 docstring const text =
2606 bformat(_("Do you want to retrieve the document"
2607 " %1$s from version control?"), file);
2608 int const ret = Alert::prompt(_("Retrieve from version control?"),
2609 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2612 // How can we know _how_ to do the checkout?
2613 // With the current VC support it has to be,
2614 // a RCS file since CVS do not have special ,v files.
2616 return loadLyXFile(s);
2624 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2626 TeXErrors::Errors::const_iterator cit = terr.begin();
2627 TeXErrors::Errors::const_iterator end = terr.end();
2629 for (; cit != end; ++cit) {
2632 int errorRow = cit->error_in_line;
2633 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2639 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2640 } while (found && id_start == id_end && pos_start == pos_end);
2642 errorList.push_back(ErrorItem(cit->error_desc,
2643 cit->error_text, id_start, pos_start, pos_end));