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>
98 #include <boost/shared_ptr.hpp>
109 using namespace lyx::support;
113 namespace Alert = frontend::Alert;
114 namespace os = support::os;
118 // Do not remove the comment below, so we get merge conflict in
119 // in independent branches.
120 int const LYX_FORMAT = 344; // ps: backref
122 typedef map<string, bool> DepClean;
123 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
130 Impl(Buffer & parent, FileName const & file, bool readonly);
144 mutable TexRow texrow;
145 Buffer const * parent_buffer;
147 /// need to regenerate .tex?
151 mutable bool lyx_clean;
153 /// is autosave needed?
154 mutable bool bak_clean;
156 /// is this a unnamed file (New...)?
162 /// name of the file the buffer is associated with.
165 /** Set to true only when the file is fully loaded.
166 * Used to prevent the premature generation of previews
167 * and by the citation inset.
169 bool file_fully_loaded;
172 mutable TocBackend toc_backend;
175 typedef pair<DocIterator, MacroData> ScopeMacro;
176 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
177 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
178 /// map from the macro name to the position map,
179 /// which maps the macro definition position to the scope and the MacroData.
180 NamePositionScopeMacroMap macros;
183 /// positions of child buffers in the buffer
184 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
185 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
186 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
187 /// position of children buffers in this buffer
188 BufferPositionMap children_positions;
189 /// map from children inclusion positions to their scope and their buffer
190 PositionScopeBufferMap position_to_children;
192 /// Container for all sort of Buffer dependant errors.
193 map<string, ErrorList> errorLists;
195 /// timestamp and checksum used to test if the file has been externally
196 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
198 unsigned long checksum_;
201 frontend::WorkAreaManager * wa_;
206 /// A cache for the bibfiles (including bibfiles of loaded child
207 /// documents), needed for appropriate update of natbib labels.
208 mutable support::FileNameList bibfilesCache_;
210 // FIXME The caching mechanism could be improved. At present, we have a
211 // cache for each Buffer, that caches all the bibliography info for that
212 // Buffer. A more efficient solution would be to have a global cache per
213 // file, and then to construct the Buffer's bibinfo from that.
214 /// A cache for bibliography info
215 mutable BiblioInfo bibinfo_;
216 /// whether the bibinfo cache is valid
217 bool bibinfoCacheValid_;
218 /// Cache of timestamps of .bib files
219 map<FileName, time_t> bibfileStatus_;
221 mutable RefCache ref_cache_;
223 /// our Text that should be wrapped in an InsetText
228 /// Creates the per buffer temporary directory
229 static FileName createBufferTmpDir()
232 // We are in our own directory. Why bother to mangle name?
233 // In fact I wrote this code to circumvent a problematic behaviour
234 // (bug?) of EMX mkstemp().
235 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
236 convert<string>(count++));
238 if (!tmpfl.createDirectory(0777)) {
239 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
240 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
241 from_utf8(tmpfl.absFilename())));
247 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
248 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
249 read_only(readonly_), filename(file), file_fully_loaded(false),
250 toc_backend(&parent), macro_lock(false), timestamp_(0),
251 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false)
253 temppath = createBufferTmpDir();
254 lyxvc.setBuffer(&parent);
256 wa_ = new frontend::WorkAreaManager;
260 Buffer::Buffer(string const & file, bool readonly)
261 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
263 LYXERR(Debug::INFO, "Buffer::Buffer()");
265 d->inset = new InsetText(*this);
266 d->inset->setAutoBreakRows(true);
267 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
273 LYXERR(Debug::INFO, "Buffer::~Buffer()");
274 // here the buffer should take care that it is
275 // saved properly, before it goes into the void.
277 // GuiView already destroyed
281 // loop over children
282 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
283 Impl::BufferPositionMap::iterator end = d->children_positions.end();
284 for (; it != end; ++it)
285 theBufferList().releaseChild(this, const_cast<Buffer *>(it->first));
287 // clear references to children in macro tables
288 d->children_positions.clear();
289 d->position_to_children.clear();
291 if (!d->temppath.destroyDirectory()) {
292 Alert::warning(_("Could not remove temporary directory"),
293 bformat(_("Could not remove the temporary directory %1$s"),
294 from_utf8(d->temppath.absFilename())));
297 // Remove any previewed LaTeX snippets associated with this buffer.
298 thePreviews().removeLoader(*this);
304 void Buffer::changed() const
311 frontend::WorkAreaManager & Buffer::workAreaManager() const
313 LASSERT(d->wa_, /**/);
318 Text & Buffer::text() const
320 return d->inset->text();
324 Inset & Buffer::inset() const
330 BufferParams & Buffer::params()
336 BufferParams const & Buffer::params() const
342 ParagraphList & Buffer::paragraphs()
344 return text().paragraphs();
348 ParagraphList const & Buffer::paragraphs() const
350 return text().paragraphs();
354 LyXVC & Buffer::lyxvc()
360 LyXVC const & Buffer::lyxvc() const
366 string const Buffer::temppath() const
368 return d->temppath.absFilename();
372 TexRow const & Buffer::texrow() const
378 TocBackend & Buffer::tocBackend() const
380 return d->toc_backend;
384 Undo & Buffer::undo()
390 string Buffer::latexName(bool const no_path) const
392 FileName latex_name = makeLatexName(d->filename);
393 return no_path ? latex_name.onlyFileName()
394 : latex_name.absFilename();
398 string Buffer::logName(LogType * type) const
400 string const filename = latexName(false);
402 if (filename.empty()) {
408 string const path = temppath();
410 FileName const fname(addName(temppath(),
411 onlyFilename(changeExtension(filename,
413 FileName const bname(
414 addName(path, onlyFilename(
415 changeExtension(filename,
416 formats.extension("literate") + ".out"))));
418 // If no Latex log or Build log is newer, show Build log
420 if (bname.exists() &&
421 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
422 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
425 return bname.absFilename();
427 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
430 return fname.absFilename();
434 void Buffer::setReadonly(bool const flag)
436 if (d->read_only != flag) {
443 void Buffer::setFileName(string const & newfile)
445 d->filename = makeAbsPath(newfile);
446 setReadonly(d->filename.isReadOnly());
451 int Buffer::readHeader(Lexer & lex)
453 int unknown_tokens = 0;
455 int begin_header_line = -1;
457 // Initialize parameters that may be/go lacking in header:
458 params().branchlist().clear();
459 params().preamble.erase();
460 params().options.erase();
461 params().master.erase();
462 params().float_placement.erase();
463 params().paperwidth.erase();
464 params().paperheight.erase();
465 params().leftmargin.erase();
466 params().rightmargin.erase();
467 params().topmargin.erase();
468 params().bottommargin.erase();
469 params().headheight.erase();
470 params().headsep.erase();
471 params().footskip.erase();
472 params().columnsep.erase();
473 params().fontsCJK.erase();
474 params().listings_params.clear();
475 params().clearLayoutModules();
476 params().clearRemovedModules();
477 params().pdfoptions().clear();
479 for (int i = 0; i < 4; ++i) {
480 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
481 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
484 ErrorList & errorList = d->errorLists["Parse"];
493 if (token == "\\end_header")
497 if (token == "\\begin_header") {
498 begin_header_line = line;
502 LYXERR(Debug::PARSER, "Handling document header token: `"
505 string unknown = params().readToken(lex, token, d->filename.onlyPath());
506 if (!unknown.empty()) {
507 if (unknown[0] != '\\' && token == "\\textclass") {
508 Alert::warning(_("Unknown document class"),
509 bformat(_("Using the default document class, because the "
510 "class %1$s is unknown."), from_utf8(unknown)));
513 docstring const s = bformat(_("Unknown token: "
517 errorList.push_back(ErrorItem(_("Document header error"),
522 if (begin_header_line) {
523 docstring const s = _("\\begin_header is missing");
524 errorList.push_back(ErrorItem(_("Document header error"),
528 params().makeDocumentClass();
530 return unknown_tokens;
535 // changed to be public and have one parameter
536 // Returns false if "\end_document" is not read (Asger)
537 bool Buffer::readDocument(Lexer & lex)
539 ErrorList & errorList = d->errorLists["Parse"];
542 if (!lex.checkFor("\\begin_document")) {
543 docstring const s = _("\\begin_document is missing");
544 errorList.push_back(ErrorItem(_("Document header error"),
548 // we are reading in a brand new document
549 LASSERT(paragraphs().empty(), /**/);
553 if (params().outputChanges) {
554 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
555 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
556 LaTeXFeatures::isAvailable("xcolor");
558 if (!dvipost && !xcolorsoul) {
559 Alert::warning(_("Changes not shown in LaTeX output"),
560 _("Changes will not be highlighted in LaTeX output, "
561 "because neither dvipost nor xcolor/soul are installed.\n"
562 "Please install these packages or redefine "
563 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
564 } else if (!xcolorsoul) {
565 Alert::warning(_("Changes not shown in LaTeX output"),
566 _("Changes will not be highlighted in LaTeX output "
567 "when using pdflatex, because xcolor and soul are not installed.\n"
568 "Please install both packages or redefine "
569 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
573 if (!params().master.empty()) {
574 FileName const master_file = makeAbsPath(params().master,
575 onlyPath(absFileName()));
576 if (isLyXFilename(master_file.absFilename())) {
577 Buffer * master = checkAndLoadLyXFile(master_file);
578 d->parent_buffer = master;
583 bool const res = text().read(*this, lex, errorList, d->inset);
586 updateMacroInstances();
591 // needed to insert the selection
592 void Buffer::insertStringAsLines(ParagraphList & pars,
593 pit_type & pit, pos_type & pos,
594 Font const & fn, docstring const & str, bool autobreakrows)
598 // insert the string, don't insert doublespace
599 bool space_inserted = true;
600 for (docstring::const_iterator cit = str.begin();
601 cit != str.end(); ++cit) {
602 Paragraph & par = pars[pit];
604 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
605 breakParagraph(params(), pars, pit, pos,
606 par.layout().isEnvironment());
609 space_inserted = true;
613 // do not insert consecutive spaces if !free_spacing
614 } else if ((*cit == ' ' || *cit == '\t') &&
615 space_inserted && !par.isFreeSpacing()) {
617 } else if (*cit == '\t') {
618 if (!par.isFreeSpacing()) {
619 // tabs are like spaces here
620 par.insertChar(pos, ' ', font, params().trackChanges);
622 space_inserted = true;
624 par.insertChar(pos, *cit, font, params().trackChanges);
626 space_inserted = true;
628 } else if (!isPrintable(*cit)) {
629 // Ignore unprintables
632 // just insert the character
633 par.insertChar(pos, *cit, font, params().trackChanges);
635 space_inserted = (*cit == ' ');
642 bool Buffer::readString(string const & s)
644 params().compressed = false;
646 // remove dummy empty par
647 paragraphs().clear();
651 FileName const name = FileName::tempName("Buffer_readString");
652 switch (readFile(lex, name, true)) {
656 // We need to call lyx2lyx, so write the input to a file
657 ofstream os(name.toFilesystemEncoding().c_str());
660 return readFile(name);
670 bool Buffer::readFile(FileName const & filename)
672 FileName fname(filename);
674 // remove dummy empty par
675 paragraphs().clear();
678 if (readFile(lex, fname) != success)
685 bool Buffer::isFullyLoaded() const
687 return d->file_fully_loaded;
691 void Buffer::setFullyLoaded(bool value)
693 d->file_fully_loaded = value;
697 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
700 LASSERT(!filename.empty(), /**/);
702 // the first (non-comment) token _must_ be...
703 if (!lex.checkFor("\\lyxformat")) {
704 Alert::error(_("Document format failure"),
705 bformat(_("%1$s is not a readable LyX document."),
706 from_utf8(filename.absFilename())));
712 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
713 // if present remove ".," from string.
714 size_t dot = tmp_format.find_first_of(".,");
715 //lyxerr << " dot found at " << dot << endl;
716 if (dot != string::npos)
717 tmp_format.erase(dot, 1);
718 int const file_format = convert<int>(tmp_format);
719 //lyxerr << "format: " << file_format << endl;
721 // save timestamp and checksum of the original disk file, making sure
722 // to not overwrite them with those of the file created in the tempdir
723 // when it has to be converted to the current format.
725 // Save the timestamp and checksum of disk file. If filename is an
726 // emergency file, save the timestamp and checksum of the original lyx file
727 // because isExternallyModified will check for this file. (BUG4193)
728 string diskfile = filename.absFilename();
729 if (suffixIs(diskfile, ".emergency"))
730 diskfile = diskfile.substr(0, diskfile.size() - 10);
731 saveCheckSum(FileName(diskfile));
734 if (file_format != LYX_FORMAT) {
737 // lyx2lyx would fail
740 FileName const tmpfile = FileName::tempName("Buffer_readFile");
741 if (tmpfile.empty()) {
742 Alert::error(_("Conversion failed"),
743 bformat(_("%1$s is from a different"
744 " version of LyX, but a temporary"
745 " file for converting it could"
747 from_utf8(filename.absFilename())));
750 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
751 if (lyx2lyx.empty()) {
752 Alert::error(_("Conversion script not found"),
753 bformat(_("%1$s is from a different"
754 " version of LyX, but the"
755 " conversion script lyx2lyx"
756 " could not be found."),
757 from_utf8(filename.absFilename())));
760 ostringstream command;
761 command << os::python()
762 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
763 << " -t " << convert<string>(LYX_FORMAT)
764 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
765 << ' ' << quoteName(filename.toFilesystemEncoding());
766 string const command_str = command.str();
768 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
770 cmd_ret const ret = runCommand(command_str);
771 if (ret.first != 0) {
772 Alert::error(_("Conversion script failed"),
773 bformat(_("%1$s is from a different version"
774 " of LyX, but the lyx2lyx script"
775 " failed to convert it."),
776 from_utf8(filename.absFilename())));
779 bool const ret = readFile(tmpfile);
780 // Do stuff with tmpfile name and buffer name here.
781 return ret ? success : failure;
786 if (readDocument(lex)) {
787 Alert::error(_("Document format failure"),
788 bformat(_("%1$s ended unexpectedly, which means"
789 " that it is probably corrupted."),
790 from_utf8(filename.absFilename())));
793 d->file_fully_loaded = true;
798 // Should probably be moved to somewhere else: BufferView? LyXView?
799 bool Buffer::save() const
801 // We don't need autosaves in the immediate future. (Asger)
802 resetAutosaveTimers();
804 string const encodedFilename = d->filename.toFilesystemEncoding();
807 bool madeBackup = false;
809 // make a backup if the file already exists
810 if (lyxrc.make_backup && fileName().exists()) {
811 backupName = FileName(absFileName() + '~');
812 if (!lyxrc.backupdir_path.empty()) {
813 string const mangledName =
814 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
815 backupName = FileName(addName(lyxrc.backupdir_path,
818 if (fileName().copyTo(backupName)) {
821 Alert::error(_("Backup failure"),
822 bformat(_("Cannot create backup file %1$s.\n"
823 "Please check whether the directory exists and is writeable."),
824 from_utf8(backupName.absFilename())));
825 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
829 // ask if the disk file has been externally modified (use checksum method)
830 if (fileName().exists() && isExternallyModified(checksum_method)) {
831 docstring const file = makeDisplayPath(absFileName(), 20);
832 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
833 "you want to overwrite this file?"), file);
834 int const ret = Alert::prompt(_("Overwrite modified file?"),
835 text, 1, 1, _("&Overwrite"), _("&Cancel"));
840 if (writeFile(d->filename)) {
844 // Saving failed, so backup is not backup
846 backupName.moveTo(d->filename);
852 bool Buffer::writeFile(FileName const & fname) const
854 if (d->read_only && fname == d->filename)
859 docstring const str = bformat(_("Saving document %1$s..."),
860 makeDisplayPath(fname.absFilename()));
863 if (params().compressed) {
864 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
865 retval = ofs && write(ofs);
867 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
868 retval = ofs && write(ofs);
872 message(str + _(" could not write file!"));
876 removeAutosaveFile(d->filename.absFilename());
878 saveCheckSum(d->filename);
879 message(str + _(" done."));
885 bool Buffer::write(ostream & ofs) const
888 // Use the standard "C" locale for file output.
889 ofs.imbue(locale::classic());
892 // The top of the file should not be written by params().
894 // write out a comment in the top of the file
895 ofs << "#LyX " << lyx_version
896 << " created this file. For more info see http://www.lyx.org/\n"
897 << "\\lyxformat " << LYX_FORMAT << "\n"
898 << "\\begin_document\n";
900 /// For each author, set 'used' to true if there is a change
901 /// by this author in the document; otherwise set it to 'false'.
902 AuthorList::Authors::const_iterator a_it = params().authors().begin();
903 AuthorList::Authors::const_iterator a_end = params().authors().end();
904 for (; a_it != a_end; ++a_it)
905 a_it->second.setUsed(false);
907 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
908 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
909 for ( ; it != end; ++it)
910 it->checkAuthors(params().authors());
912 // now write out the buffer parameters.
913 ofs << "\\begin_header\n";
914 params().writeFile(ofs);
915 ofs << "\\end_header\n";
918 ofs << "\n\\begin_body\n";
919 text().write(*this, ofs);
920 ofs << "\n\\end_body\n";
922 // Write marker that shows file is complete
923 ofs << "\\end_document" << endl;
925 // Shouldn't really be needed....
928 // how to check if close went ok?
929 // Following is an attempt... (BE 20001011)
931 // good() returns false if any error occured, including some
933 // bad() returns true if something bad happened in the buffer,
934 // which should include file system full errors.
939 lyxerr << "File was not closed properly." << endl;
946 bool Buffer::makeLaTeXFile(FileName const & fname,
947 string const & original_path,
948 OutputParams const & runparams,
949 bool output_preamble, bool output_body) const
951 string const encoding = runparams.encoding->iconvName();
952 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
955 try { ofs.reset(encoding); }
956 catch (iconv_codecvt_facet_exception & e) {
957 lyxerr << "Caught iconv exception: " << e.what() << endl;
958 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
959 "verify that the support software for your encoding (%1$s) is "
960 "properly installed"), from_ascii(encoding)));
963 if (!openFileWrite(ofs, fname))
966 //TexStream ts(ofs.rdbuf(), &texrow());
967 ErrorList & errorList = d->errorLists["Export"];
969 bool failed_export = false;
972 writeLaTeXSource(ofs, original_path,
973 runparams, output_preamble, output_body);
975 catch (EncodingException & e) {
976 odocstringstream ods;
977 ods.put(e.failed_char);
979 oss << "0x" << hex << e.failed_char << dec;
980 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
981 " (code point %2$s)"),
982 ods.str(), from_utf8(oss.str()));
983 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
984 "representable in the chosen encoding.\n"
985 "Changing the document encoding to utf8 could help."),
986 e.par_id, e.pos, e.pos + 1));
987 failed_export = true;
989 catch (iconv_codecvt_facet_exception & e) {
990 errorList.push_back(ErrorItem(_("iconv conversion failed"),
991 _(e.what()), -1, 0, 0));
992 failed_export = true;
994 catch (exception const & e) {
995 errorList.push_back(ErrorItem(_("conversion failed"),
996 _(e.what()), -1, 0, 0));
997 failed_export = true;
1000 lyxerr << "Caught some really weird exception..." << endl;
1006 failed_export = true;
1007 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1011 return !failed_export;
1015 void Buffer::writeLaTeXSource(odocstream & os,
1016 string const & original_path,
1017 OutputParams const & runparams_in,
1018 bool const output_preamble, bool const output_body) const
1020 // The child documents, if any, shall be already loaded at this point.
1022 OutputParams runparams = runparams_in;
1024 // Classify the unicode characters appearing in math insets
1025 Encodings::initUnicodeMath(*this);
1027 // validate the buffer.
1028 LYXERR(Debug::LATEX, " Validating buffer...");
1029 LaTeXFeatures features(*this, params(), runparams);
1031 LYXERR(Debug::LATEX, " Buffer validation done.");
1033 // The starting paragraph of the coming rows is the
1034 // first paragraph of the document. (Asger)
1035 if (output_preamble && runparams.nice) {
1036 os << "%% LyX " << lyx_version << " created this file. "
1037 "For more info, see http://www.lyx.org/.\n"
1038 "%% Do not edit unless you really know what "
1040 d->texrow.newline();
1041 d->texrow.newline();
1043 LYXERR(Debug::INFO, "lyx document header finished");
1045 // Don't move this behind the parent_buffer=0 code below,
1046 // because then the macros will not get the right "redefinition"
1047 // flag as they don't see the parent macros which are output before.
1050 // fold macros if possible, still with parent buffer as the
1051 // macros will be put in the prefix anyway.
1052 updateMacroInstances();
1054 // There are a few differences between nice LaTeX and usual files:
1055 // usual is \batchmode and has a
1056 // special input@path to allow the including of figures
1057 // with either \input or \includegraphics (what figinsets do).
1058 // input@path is set when the actual parameter
1059 // original_path is set. This is done for usual tex-file, but not
1060 // for nice-latex-file. (Matthias 250696)
1061 // Note that input@path is only needed for something the user does
1062 // in the preamble, included .tex files or ERT, files included by
1063 // LyX work without it.
1064 if (output_preamble) {
1065 if (!runparams.nice) {
1066 // code for usual, NOT nice-latex-file
1067 os << "\\batchmode\n"; // changed
1068 // from \nonstopmode
1069 d->texrow.newline();
1071 if (!original_path.empty()) {
1073 // We don't know the encoding of inputpath
1074 docstring const inputpath = from_utf8(latex_path(original_path));
1075 os << "\\makeatletter\n"
1076 << "\\def\\input@path{{"
1077 << inputpath << "/}}\n"
1078 << "\\makeatother\n";
1079 d->texrow.newline();
1080 d->texrow.newline();
1081 d->texrow.newline();
1084 // get parent macros (if this buffer has a parent) which will be
1085 // written at the document begin further down.
1086 MacroSet parentMacros;
1087 listParentMacros(parentMacros, features);
1089 // Write the preamble
1090 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1092 runparams.use_japanese = features.isRequired("japanese");
1098 os << "\\begin{document}\n";
1099 d->texrow.newline();
1101 // output the parent macros
1102 MacroSet::iterator it = parentMacros.begin();
1103 MacroSet::iterator end = parentMacros.end();
1104 for (; it != end; ++it)
1105 (*it)->write(os, true);
1106 } // output_preamble
1108 d->texrow.start(paragraphs().begin()->id(), 0);
1110 LYXERR(Debug::INFO, "preamble finished, now the body.");
1112 // if we are doing a real file with body, even if this is the
1113 // child of some other buffer, let's cut the link here.
1114 // This happens for example if only a child document is printed.
1115 Buffer const * save_parent = 0;
1116 if (output_preamble) {
1117 save_parent = d->parent_buffer;
1118 d->parent_buffer = 0;
1122 latexParagraphs(*this, text(), os, d->texrow, runparams);
1124 // Restore the parenthood if needed
1125 if (output_preamble)
1126 d->parent_buffer = save_parent;
1128 // add this just in case after all the paragraphs
1130 d->texrow.newline();
1132 if (output_preamble) {
1133 os << "\\end{document}\n";
1134 d->texrow.newline();
1135 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1137 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1139 runparams_in.encoding = runparams.encoding;
1141 // Just to be sure. (Asger)
1142 d->texrow.newline();
1144 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1145 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1149 bool Buffer::isLatex() const
1151 return params().documentClass().outputType() == LATEX;
1155 bool Buffer::isLiterate() const
1157 return params().documentClass().outputType() == LITERATE;
1161 bool Buffer::isDocBook() const
1163 return params().documentClass().outputType() == DOCBOOK;
1167 void Buffer::makeDocBookFile(FileName const & fname,
1168 OutputParams const & runparams,
1169 bool const body_only) const
1171 LYXERR(Debug::LATEX, "makeDocBookFile...");
1174 if (!openFileWrite(ofs, fname))
1177 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1181 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1185 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1186 OutputParams const & runparams,
1187 bool const only_body) const
1189 LaTeXFeatures features(*this, params(), runparams);
1194 DocumentClass const & tclass = params().documentClass();
1195 string const top_element = tclass.latexname();
1198 if (runparams.flavor == OutputParams::XML)
1199 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1202 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1205 if (! tclass.class_header().empty())
1206 os << from_ascii(tclass.class_header());
1207 else if (runparams.flavor == OutputParams::XML)
1208 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1209 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1211 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1213 docstring preamble = from_utf8(params().preamble);
1214 if (runparams.flavor != OutputParams::XML ) {
1215 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1216 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1217 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1218 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1221 string const name = runparams.nice
1222 ? changeExtension(absFileName(), ".sgml") : fname;
1223 preamble += features.getIncludedFiles(name);
1224 preamble += features.getLyXSGMLEntities();
1226 if (!preamble.empty()) {
1227 os << "\n [ " << preamble << " ]";
1232 string top = top_element;
1234 if (runparams.flavor == OutputParams::XML)
1235 top += params().language->code();
1237 top += params().language->code().substr(0, 2);
1240 if (!params().options.empty()) {
1242 top += params().options;
1245 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1246 << " file was created by LyX " << lyx_version
1247 << "\n See http://www.lyx.org/ for more information -->\n";
1249 params().documentClass().counters().reset();
1253 sgml::openTag(os, top);
1255 docbookParagraphs(paragraphs(), *this, os, runparams);
1256 sgml::closeTag(os, top_element);
1260 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1261 // Other flags: -wall -v0 -x
1262 int Buffer::runChktex()
1266 // get LaTeX-Filename
1267 FileName const path(temppath());
1268 string const name = addName(path.absFilename(), latexName());
1269 string const org_path = filePath();
1271 PathChanger p(path); // path to LaTeX file
1272 message(_("Running chktex..."));
1274 // Generate the LaTeX file if neccessary
1275 OutputParams runparams(¶ms().encoding());
1276 runparams.flavor = OutputParams::LATEX;
1277 runparams.nice = false;
1278 makeLaTeXFile(FileName(name), org_path, runparams);
1281 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1282 int const res = chktex.run(terr); // run chktex
1285 Alert::error(_("chktex failure"),
1286 _("Could not run chktex successfully."));
1287 } else if (res > 0) {
1288 ErrorList & errlist = d->errorLists["ChkTeX"];
1290 bufferErrors(terr, errlist);
1301 void Buffer::validate(LaTeXFeatures & features) const
1303 params().validate(features);
1307 for_each(paragraphs().begin(), paragraphs().end(),
1308 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1310 if (lyxerr.debugging(Debug::LATEX)) {
1311 features.showStruct();
1316 void Buffer::getLabelList(vector<docstring> & list) const
1318 // If this is a child document, use the parent's list instead.
1319 if (d->parent_buffer) {
1320 d->parent_buffer->getLabelList(list);
1325 Toc & toc = d->toc_backend.toc("label");
1326 TocIterator toc_it = toc.begin();
1327 TocIterator end = toc.end();
1328 for (; toc_it != end; ++toc_it) {
1329 if (toc_it->depth() == 0)
1330 list.push_back(toc_it->str());
1335 void Buffer::updateBibfilesCache() const
1337 // If this is a child document, use the parent's cache instead.
1338 if (d->parent_buffer) {
1339 d->parent_buffer->updateBibfilesCache();
1343 d->bibfilesCache_.clear();
1344 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1345 if (it->lyxCode() == BIBTEX_CODE) {
1346 InsetBibtex const & inset =
1347 static_cast<InsetBibtex const &>(*it);
1348 support::FileNameList const bibfiles = inset.getBibFiles();
1349 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1352 } else if (it->lyxCode() == INCLUDE_CODE) {
1353 InsetInclude & inset =
1354 static_cast<InsetInclude &>(*it);
1355 inset.updateBibfilesCache();
1356 support::FileNameList const & bibfiles =
1357 inset.getBibfilesCache(*this);
1358 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1363 // the bibinfo cache is now invalid
1364 d->bibinfoCacheValid_ = false;
1368 void Buffer::invalidateBibinfoCache()
1370 d->bibinfoCacheValid_ = false;
1374 support::FileNameList const & Buffer::getBibfilesCache() const
1376 // If this is a child document, use the parent's cache instead.
1377 if (d->parent_buffer)
1378 return d->parent_buffer->getBibfilesCache();
1380 // We update the cache when first used instead of at loading time.
1381 if (d->bibfilesCache_.empty())
1382 const_cast<Buffer *>(this)->updateBibfilesCache();
1384 return d->bibfilesCache_;
1388 BiblioInfo const & Buffer::masterBibInfo() const
1390 // if this is a child document and the parent is already loaded
1391 // use the parent's list instead [ale990412]
1392 Buffer const * const tmp = masterBuffer();
1395 return tmp->masterBibInfo();
1396 return localBibInfo();
1400 BiblioInfo const & Buffer::localBibInfo() const
1402 if (d->bibinfoCacheValid_) {
1403 support::FileNameList const & bibfilesCache = getBibfilesCache();
1404 // compare the cached timestamps with the actual ones.
1405 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1406 support::FileNameList::const_iterator en = bibfilesCache.end();
1407 for (; ei != en; ++ ei) {
1408 time_t lastw = ei->lastModified();
1409 if (lastw != d->bibfileStatus_[*ei]) {
1410 d->bibinfoCacheValid_ = false;
1411 d->bibfileStatus_[*ei] = lastw;
1417 if (!d->bibinfoCacheValid_) {
1418 d->bibinfo_.clear();
1419 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1420 it->fillWithBibKeys(d->bibinfo_, it);
1421 d->bibinfoCacheValid_ = true;
1427 bool Buffer::isDepClean(string const & name) const
1429 DepClean::const_iterator const it = d->dep_clean.find(name);
1430 if (it == d->dep_clean.end())
1436 void Buffer::markDepClean(string const & name)
1438 d->dep_clean[name] = true;
1442 bool Buffer::dispatch(string const & command, bool * result)
1444 return dispatch(lyxaction.lookupFunc(command), result);
1448 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1450 bool dispatched = true;
1452 switch (func.action) {
1453 case LFUN_BUFFER_EXPORT: {
1454 bool const tmp = doExport(to_utf8(func.argument()), false);
1460 case LFUN_BRANCH_ACTIVATE:
1461 case LFUN_BRANCH_DEACTIVATE: {
1462 BranchList & branchList = params().branchlist();
1463 docstring const branchName = func.argument();
1464 Branch * branch = branchList.find(branchName);
1466 LYXERR0("Branch " << branchName << " does not exist.");
1468 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1480 void Buffer::changeLanguage(Language const * from, Language const * to)
1482 LASSERT(from, /**/);
1485 for_each(par_iterator_begin(),
1487 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1491 bool Buffer::isMultiLingual() const
1493 ParConstIterator end = par_iterator_end();
1494 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1495 if (it->isMultiLingual(params()))
1502 DocIterator Buffer::getParFromID(int const id) const
1505 // John says this is called with id == -1 from undo
1506 lyxerr << "getParFromID(), id: " << id << endl;
1507 return doc_iterator_end(inset());
1510 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1511 if (it.paragraph().id() == id)
1514 return doc_iterator_end(inset());
1518 bool Buffer::hasParWithID(int const id) const
1520 return !getParFromID(id).atEnd();
1524 ParIterator Buffer::par_iterator_begin()
1526 return ParIterator(doc_iterator_begin(inset()));
1530 ParIterator Buffer::par_iterator_end()
1532 return ParIterator(doc_iterator_end(inset()));
1536 ParConstIterator Buffer::par_iterator_begin() const
1538 return lyx::par_const_iterator_begin(inset());
1542 ParConstIterator Buffer::par_iterator_end() const
1544 return lyx::par_const_iterator_end(inset());
1548 Language const * Buffer::language() const
1550 return params().language;
1554 docstring const Buffer::B_(string const & l10n) const
1556 return params().B_(l10n);
1560 bool Buffer::isClean() const
1562 return d->lyx_clean;
1566 bool Buffer::isBakClean() const
1568 return d->bak_clean;
1572 bool Buffer::isExternallyModified(CheckMethod method) const
1574 LASSERT(d->filename.exists(), /**/);
1575 // if method == timestamp, check timestamp before checksum
1576 return (method == checksum_method
1577 || d->timestamp_ != d->filename.lastModified())
1578 && d->checksum_ != d->filename.checksum();
1582 void Buffer::saveCheckSum(FileName const & file) const
1584 if (file.exists()) {
1585 d->timestamp_ = file.lastModified();
1586 d->checksum_ = file.checksum();
1588 // in the case of save to a new file.
1595 void Buffer::markClean() const
1597 if (!d->lyx_clean) {
1598 d->lyx_clean = true;
1601 // if the .lyx file has been saved, we don't need an
1603 d->bak_clean = true;
1607 void Buffer::markBakClean() const
1609 d->bak_clean = true;
1613 void Buffer::setUnnamed(bool flag)
1619 bool Buffer::isUnnamed() const
1625 // FIXME: this function should be moved to buffer_pimpl.C
1626 void Buffer::markDirty()
1629 d->lyx_clean = false;
1632 d->bak_clean = false;
1634 DepClean::iterator it = d->dep_clean.begin();
1635 DepClean::const_iterator const end = d->dep_clean.end();
1637 for (; it != end; ++it)
1642 FileName Buffer::fileName() const
1648 string Buffer::absFileName() const
1650 return d->filename.absFilename();
1654 string Buffer::filePath() const
1656 return d->filename.onlyPath().absFilename() + "/";
1660 bool Buffer::isReadonly() const
1662 return d->read_only;
1666 void Buffer::setParent(Buffer const * buffer)
1668 // Avoids recursive include.
1669 d->parent_buffer = buffer == this ? 0 : buffer;
1674 Buffer const * Buffer::parent()
1676 return d->parent_buffer;
1680 Buffer const * Buffer::masterBuffer() const
1682 if (!d->parent_buffer)
1685 return d->parent_buffer->masterBuffer();
1689 bool Buffer::isChild(Buffer * child) const
1691 return d->children_positions.find(child) != d->children_positions.end();
1695 template<typename M>
1696 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1701 typename M::iterator it = m.lower_bound(x);
1702 if (it == m.begin())
1710 MacroData const * Buffer::getBufferMacro(docstring const & name,
1711 DocIterator const & pos) const
1713 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1715 // if paragraphs have no macro context set, pos will be empty
1719 // we haven't found anything yet
1720 DocIterator bestPos = par_iterator_begin();
1721 MacroData const * bestData = 0;
1723 // find macro definitions for name
1724 Impl::NamePositionScopeMacroMap::iterator nameIt
1725 = d->macros.find(name);
1726 if (nameIt != d->macros.end()) {
1727 // find last definition in front of pos or at pos itself
1728 Impl::PositionScopeMacroMap::const_iterator it
1729 = greatest_below(nameIt->second, pos);
1730 if (it != nameIt->second.end()) {
1732 // scope ends behind pos?
1733 if (pos < it->second.first) {
1734 // Looks good, remember this. If there
1735 // is no external macro behind this,
1736 // we found the right one already.
1737 bestPos = it->first;
1738 bestData = &it->second.second;
1742 // try previous macro if there is one
1743 if (it == nameIt->second.begin())
1750 // find macros in included files
1751 Impl::PositionScopeBufferMap::const_iterator it
1752 = greatest_below(d->position_to_children, pos);
1753 if (it == d->position_to_children.end())
1754 // no children before
1758 // do we know something better (i.e. later) already?
1759 if (it->first < bestPos )
1762 // scope ends behind pos?
1763 if (pos < it->second.first) {
1764 // look for macro in external file
1765 d->macro_lock = true;
1766 MacroData const * data
1767 = it->second.second->getMacro(name, false);
1768 d->macro_lock = false;
1770 bestPos = it->first;
1776 // try previous file if there is one
1777 if (it == d->position_to_children.begin())
1782 // return the best macro we have found
1787 MacroData const * Buffer::getMacro(docstring const & name,
1788 DocIterator const & pos, bool global) const
1793 // query buffer macros
1794 MacroData const * data = getBufferMacro(name, pos);
1798 // If there is a master buffer, query that
1799 if (d->parent_buffer) {
1800 d->macro_lock = true;
1801 MacroData const * macro = d->parent_buffer->getMacro(
1802 name, *this, false);
1803 d->macro_lock = false;
1809 data = MacroTable::globalMacros().get(name);
1818 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1820 // set scope end behind the last paragraph
1821 DocIterator scope = par_iterator_begin();
1822 scope.pit() = scope.lastpit() + 1;
1824 return getMacro(name, scope, global);
1828 MacroData const * Buffer::getMacro(docstring const & name,
1829 Buffer const & child, bool global) const
1831 // look where the child buffer is included first
1832 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1833 if (it == d->children_positions.end())
1836 // check for macros at the inclusion position
1837 return getMacro(name, it->second, global);
1841 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1843 pit_type lastpit = it.lastpit();
1845 // look for macros in each paragraph
1846 while (it.pit() <= lastpit) {
1847 Paragraph & par = it.paragraph();
1849 // iterate over the insets of the current paragraph
1850 InsetList const & insets = par.insetList();
1851 InsetList::const_iterator iit = insets.begin();
1852 InsetList::const_iterator end = insets.end();
1853 for (; iit != end; ++iit) {
1854 it.pos() = iit->pos;
1856 // is it a nested text inset?
1857 if (iit->inset->asInsetText()) {
1858 // Inset needs its own scope?
1859 InsetText const * itext
1860 = iit->inset->asInsetText();
1861 bool newScope = itext->isMacroScope();
1863 // scope which ends just behind the inset
1864 DocIterator insetScope = it;
1867 // collect macros in inset
1868 it.push_back(CursorSlice(*iit->inset));
1869 updateMacros(it, newScope ? insetScope : scope);
1874 // is it an external file?
1875 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1876 // get buffer of external file
1877 InsetCommand const & inset
1878 = static_cast<InsetCommand const &>(*iit->inset);
1879 InsetCommandParams const & ip = inset.params();
1880 d->macro_lock = true;
1881 Buffer * child = loadIfNeeded(*this, ip);
1882 d->macro_lock = false;
1886 // register its position, but only when it is
1887 // included first in the buffer
1888 if (d->children_positions.find(child)
1889 == d->children_positions.end())
1890 d->children_positions[child] = it;
1892 // register child with its scope
1893 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1897 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1901 MathMacroTemplate & macroTemplate
1902 = static_cast<MathMacroTemplate &>(*iit->inset);
1903 MacroContext mc(*this, it);
1904 macroTemplate.updateToContext(mc);
1907 bool valid = macroTemplate.validMacro();
1908 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1909 // then the BufferView's cursor will be invalid in
1910 // some cases which leads to crashes.
1915 d->macros[macroTemplate.name()][it] =
1916 Impl::ScopeMacro(scope, MacroData(*this, it));
1926 void Buffer::updateMacros() const
1931 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1933 // start with empty table
1935 d->children_positions.clear();
1936 d->position_to_children.clear();
1938 // Iterate over buffer, starting with first paragraph
1939 // The scope must be bigger than any lookup DocIterator
1940 // later. For the global lookup, lastpit+1 is used, hence
1941 // we use lastpit+2 here.
1942 DocIterator it = par_iterator_begin();
1943 DocIterator outerScope = it;
1944 outerScope.pit() = outerScope.lastpit() + 2;
1945 updateMacros(it, outerScope);
1949 void Buffer::updateMacroInstances() const
1951 LYXERR(Debug::MACROS, "updateMacroInstances for "
1952 << d->filename.onlyFileName());
1953 DocIterator it = doc_iterator_begin(inset());
1954 DocIterator end = doc_iterator_end(inset());
1955 for (; it != end; it.forwardPos()) {
1956 // look for MathData cells in InsetMathNest insets
1957 Inset * inset = it.nextInset();
1961 InsetMath * minset = inset->asInsetMath();
1965 // update macro in all cells of the InsetMathNest
1966 DocIterator::idx_type n = minset->nargs();
1967 MacroContext mc = MacroContext(*this, it);
1968 for (DocIterator::idx_type i = 0; i < n; ++i) {
1969 MathData & data = minset->cell(i);
1970 data.updateMacros(0, mc);
1976 void Buffer::listMacroNames(MacroNameSet & macros) const
1981 d->macro_lock = true;
1983 // loop over macro names
1984 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1985 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1986 for (; nameIt != nameEnd; ++nameIt)
1987 macros.insert(nameIt->first);
1989 // loop over children
1990 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1991 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1992 for (; it != end; ++it)
1993 it->first->listMacroNames(macros);
1996 if (d->parent_buffer)
1997 d->parent_buffer->listMacroNames(macros);
1999 d->macro_lock = false;
2003 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2005 if (!d->parent_buffer)
2009 d->parent_buffer->listMacroNames(names);
2012 MacroNameSet::iterator it = names.begin();
2013 MacroNameSet::iterator end = names.end();
2014 for (; it != end; ++it) {
2016 MacroData const * data =
2017 d->parent_buffer->getMacro(*it, *this, false);
2019 macros.insert(data);
2021 // we cannot access the original MathMacroTemplate anymore
2022 // here to calls validate method. So we do its work here manually.
2023 // FIXME: somehow make the template accessible here.
2024 if (data->optionals() > 0)
2025 features.require("xargs");
2031 Buffer::References & Buffer::references(docstring const & label)
2033 if (d->parent_buffer)
2034 return const_cast<Buffer *>(masterBuffer())->references(label);
2036 RefCache::iterator it = d->ref_cache_.find(label);
2037 if (it != d->ref_cache_.end())
2038 return it->second.second;
2040 static InsetLabel const * dummy_il = 0;
2041 static References const dummy_refs;
2042 it = d->ref_cache_.insert(
2043 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2044 return it->second.second;
2048 Buffer::References const & Buffer::references(docstring const & label) const
2050 return const_cast<Buffer *>(this)->references(label);
2054 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2056 masterBuffer()->d->ref_cache_[label].first = il;
2060 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2062 return masterBuffer()->d->ref_cache_[label].first;
2066 void Buffer::clearReferenceCache() const
2068 if (!d->parent_buffer)
2069 d->ref_cache_.clear();
2073 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2076 //FIXME: This does not work for child documents yet.
2077 LASSERT(code == CITE_CODE, /**/);
2078 // Check if the label 'from' appears more than once
2079 vector<docstring> labels;
2081 BiblioInfo const & keys = masterBibInfo();
2082 BiblioInfo::const_iterator bit = keys.begin();
2083 BiblioInfo::const_iterator bend = keys.end();
2085 for (; bit != bend; ++bit)
2087 labels.push_back(bit->first);
2090 if (count(labels.begin(), labels.end(), from) > 1)
2093 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2094 if (it->lyxCode() == code) {
2095 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2096 docstring const oldValue = inset.getParam(paramName);
2097 if (oldValue == from)
2098 inset.setParam(paramName, to);
2104 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2105 pit_type par_end, bool full_source) const
2107 OutputParams runparams(¶ms().encoding());
2108 runparams.nice = true;
2109 runparams.flavor = OutputParams::LATEX;
2110 runparams.linelen = lyxrc.plaintext_linelen;
2111 // No side effect of file copying and image conversion
2112 runparams.dryrun = true;
2116 os << "% " << _("Preview source code") << "\n\n";
2117 d->texrow.newline();
2118 d->texrow.newline();
2120 writeLaTeXSource(os, filePath(), runparams, true, true);
2122 writeDocBookSource(os, absFileName(), runparams, false);
2124 runparams.par_begin = par_begin;
2125 runparams.par_end = par_end;
2126 if (par_begin + 1 == par_end) {
2128 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2132 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2133 convert<docstring>(par_begin),
2134 convert<docstring>(par_end - 1))
2137 d->texrow.newline();
2138 d->texrow.newline();
2139 // output paragraphs
2141 latexParagraphs(*this, text(), os, d->texrow, runparams);
2144 docbookParagraphs(paragraphs(), *this, os, runparams);
2149 ErrorList & Buffer::errorList(string const & type) const
2151 static ErrorList emptyErrorList;
2152 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2153 if (I == d->errorLists.end())
2154 return emptyErrorList;
2160 void Buffer::updateTocItem(std::string const & type,
2161 DocIterator const & dit) const
2164 gui_->updateTocItem(type, dit);
2168 void Buffer::structureChanged() const
2171 gui_->structureChanged();
2175 void Buffer::errors(string const & err) const
2182 void Buffer::message(docstring const & msg) const
2189 void Buffer::setBusy(bool on) const
2196 void Buffer::setReadOnly(bool on) const
2199 d->wa_->setReadOnly(on);
2203 void Buffer::updateTitles() const
2206 d->wa_->updateTitles();
2210 void Buffer::resetAutosaveTimers() const
2213 gui_->resetAutosaveTimers();
2217 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2226 class AutoSaveBuffer : public ForkedProcess {
2229 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2230 : buffer_(buffer), fname_(fname) {}
2232 virtual boost::shared_ptr<ForkedProcess> clone() const
2234 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2239 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2240 from_utf8(fname_.absFilename())));
2241 return run(DontWait);
2245 virtual int generateChild();
2247 Buffer const & buffer_;
2252 int AutoSaveBuffer::generateChild()
2254 // tmp_ret will be located (usually) in /tmp
2255 // will that be a problem?
2256 // Note that this calls ForkedCalls::fork(), so it's
2257 // ok cross-platform.
2258 pid_t const pid = fork();
2259 // If you want to debug the autosave
2260 // you should set pid to -1, and comment out the fork.
2261 if (pid != 0 && pid != -1)
2264 // pid = -1 signifies that lyx was unable
2265 // to fork. But we will do the save
2267 bool failed = false;
2268 FileName const tmp_ret = FileName::tempName("lyxauto");
2269 if (!tmp_ret.empty()) {
2270 buffer_.writeFile(tmp_ret);
2271 // assume successful write of tmp_ret
2272 if (!tmp_ret.moveTo(fname_))
2278 // failed to write/rename tmp_ret so try writing direct
2279 if (!buffer_.writeFile(fname_)) {
2280 // It is dangerous to do this in the child,
2281 // but safe in the parent, so...
2282 if (pid == -1) // emit message signal.
2283 buffer_.message(_("Autosave failed!"));
2287 if (pid == 0) // we are the child so...
2296 // Perfect target for a thread...
2297 void Buffer::autoSave() const
2299 if (isBakClean() || isReadonly()) {
2300 // We don't save now, but we'll try again later
2301 resetAutosaveTimers();
2305 // emit message signal.
2306 message(_("Autosaving current document..."));
2308 // create autosave filename
2309 string fname = filePath();
2311 fname += d->filename.onlyFileName();
2314 AutoSaveBuffer autosave(*this, FileName(fname));
2318 resetAutosaveTimers();
2322 string Buffer::bufferFormat() const
2328 if (params().encoding().package() == Encoding::japanese)
2334 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2335 string & result_file) const
2337 string backend_format;
2338 OutputParams runparams(¶ms().encoding());
2339 runparams.flavor = OutputParams::LATEX;
2340 runparams.linelen = lyxrc.plaintext_linelen;
2341 vector<string> backs = backends();
2342 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2343 // Get shortest path to format
2344 Graph::EdgePath path;
2345 for (vector<string>::const_iterator it = backs.begin();
2346 it != backs.end(); ++it) {
2347 Graph::EdgePath p = theConverters().getPath(*it, format);
2348 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2349 backend_format = *it;
2354 runparams.flavor = theConverters().getFlavor(path);
2356 Alert::error(_("Couldn't export file"),
2357 bformat(_("No information for exporting the format %1$s."),
2358 formats.prettyName(format)));
2362 backend_format = format;
2363 // FIXME: Don't hardcode format names here, but use a flag
2364 if (backend_format == "pdflatex")
2365 runparams.flavor = OutputParams::PDFLATEX;
2368 string filename = latexName(false);
2369 filename = addName(temppath(), filename);
2370 filename = changeExtension(filename,
2371 formats.extension(backend_format));
2374 updateMacroInstances();
2376 // Plain text backend
2377 if (backend_format == "text")
2378 writePlaintextFile(*this, FileName(filename), runparams);
2380 else if (backend_format == "lyx")
2381 writeFile(FileName(filename));
2383 else if (isDocBook()) {
2384 runparams.nice = !put_in_tempdir;
2385 makeDocBookFile(FileName(filename), runparams);
2388 else if (backend_format == format) {
2389 runparams.nice = true;
2390 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2392 } else if (!lyxrc.tex_allows_spaces
2393 && contains(filePath(), ' ')) {
2394 Alert::error(_("File name error"),
2395 _("The directory path to the document cannot contain spaces."));
2398 runparams.nice = false;
2399 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2403 string const error_type = (format == "program")
2404 ? "Build" : bufferFormat();
2405 ErrorList & error_list = d->errorLists[error_type];
2406 string const ext = formats.extension(format);
2407 FileName const tmp_result_file(changeExtension(filename, ext));
2408 bool const success = theConverters().convert(this, FileName(filename),
2409 tmp_result_file, FileName(absFileName()), backend_format, format,
2411 // Emit the signal to show the error list.
2412 if (format != backend_format)
2417 if (put_in_tempdir) {
2418 result_file = tmp_result_file.absFilename();
2422 result_file = changeExtension(absFileName(), ext);
2423 // We need to copy referenced files (e. g. included graphics
2424 // if format == "dvi") to the result dir.
2425 vector<ExportedFile> const files =
2426 runparams.exportdata->externalFiles(format);
2427 string const dest = onlyPath(result_file);
2428 CopyStatus status = SUCCESS;
2429 for (vector<ExportedFile>::const_iterator it = files.begin();
2430 it != files.end() && status != CANCEL; ++it) {
2431 string const fmt = formats.getFormatFromFile(it->sourceName);
2432 status = copyFile(fmt, it->sourceName,
2433 makeAbsPath(it->exportName, dest),
2434 it->exportName, status == FORCE);
2436 if (status == CANCEL) {
2437 message(_("Document export cancelled."));
2438 } else if (tmp_result_file.exists()) {
2439 // Finally copy the main file
2440 status = copyFile(format, tmp_result_file,
2441 FileName(result_file), result_file,
2443 message(bformat(_("Document exported as %1$s "
2445 formats.prettyName(format),
2446 makeDisplayPath(result_file)));
2448 // This must be a dummy converter like fax (bug 1888)
2449 message(bformat(_("Document exported as %1$s"),
2450 formats.prettyName(format)));
2457 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2460 return doExport(format, put_in_tempdir, result_file);
2464 bool Buffer::preview(string const & format) const
2467 if (!doExport(format, true, result_file))
2469 return formats.view(*this, FileName(result_file), format);
2473 bool Buffer::isExportable(string const & format) const
2475 vector<string> backs = backends();
2476 for (vector<string>::const_iterator it = backs.begin();
2477 it != backs.end(); ++it)
2478 if (theConverters().isReachable(*it, format))
2484 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2486 vector<string> backs = backends();
2487 vector<Format const *> result =
2488 theConverters().getReachable(backs[0], only_viewable, true);
2489 for (vector<string>::const_iterator it = backs.begin() + 1;
2490 it != backs.end(); ++it) {
2491 vector<Format const *> r =
2492 theConverters().getReachable(*it, only_viewable, false);
2493 result.insert(result.end(), r.begin(), r.end());
2499 vector<string> Buffer::backends() const
2502 if (params().baseClass()->isTeXClassAvailable()) {
2503 v.push_back(bufferFormat());
2504 // FIXME: Don't hardcode format names here, but use a flag
2505 if (v.back() == "latex")
2506 v.push_back("pdflatex");
2508 v.push_back("text");
2514 bool Buffer::readFileHelper(FileName const & s)
2516 // File information about normal file
2518 docstring const file = makeDisplayPath(s.absFilename(), 50);
2519 docstring text = bformat(_("The specified document\n%1$s"
2520 "\ncould not be read."), file);
2521 Alert::error(_("Could not read document"), text);
2525 // Check if emergency save file exists and is newer.
2526 FileName const e(s.absFilename() + ".emergency");
2528 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2529 docstring const file = makeDisplayPath(s.absFilename(), 20);
2530 docstring const text =
2531 bformat(_("An emergency save of the document "
2533 "Recover emergency save?"), file);
2534 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2535 _("&Recover"), _("&Load Original"),
2539 // the file is not saved if we load the emergency file.
2549 // Now check if autosave file is newer.
2550 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2552 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2553 docstring const file = makeDisplayPath(s.absFilename(), 20);
2554 docstring const text =
2555 bformat(_("The backup of the document "
2556 "%1$s is newer.\n\nLoad the "
2557 "backup instead?"), file);
2558 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2559 _("&Load backup"), _("Load &original"),
2563 // the file is not saved if we load the autosave file.
2567 // Here we delete the autosave
2578 bool Buffer::loadLyXFile(FileName const & s)
2580 if (s.isReadableFile()) {
2581 if (readFileHelper(s)) {
2582 lyxvc().file_found_hook(s);
2583 if (!s.isWritable())
2588 docstring const file = makeDisplayPath(s.absFilename(), 20);
2589 // Here we probably should run
2590 if (LyXVC::file_not_found_hook(s)) {
2591 docstring const text =
2592 bformat(_("Do you want to retrieve the document"
2593 " %1$s from version control?"), file);
2594 int const ret = Alert::prompt(_("Retrieve from version control?"),
2595 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2598 // How can we know _how_ to do the checkout?
2599 // With the current VC support it has to be,
2600 // a RCS file since CVS do not have special ,v files.
2602 return loadLyXFile(s);
2610 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2612 TeXErrors::Errors::const_iterator cit = terr.begin();
2613 TeXErrors::Errors::const_iterator end = terr.end();
2615 for (; cit != end; ++cit) {
2618 int errorRow = cit->error_in_line;
2619 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2625 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2626 } while (found && id_start == id_end && pos_start == pos_end);
2628 errorList.push_back(ErrorItem(cit->error_desc,
2629 cit->error_text, id_start, pos_start, pos_end));