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/assert.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 int const LYX_FORMAT = 328;
120 typedef map<string, bool> DepClean;
121 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
128 Impl(Buffer & parent, FileName const & file, bool readonly);
141 mutable TexRow texrow;
142 Buffer const * parent_buffer;
144 /// need to regenerate .tex?
148 mutable bool lyx_clean;
150 /// is autosave needed?
151 mutable bool bak_clean;
153 /// is this a unnamed file (New...)?
159 /// name of the file the buffer is associated with.
162 /** Set to true only when the file is fully loaded.
163 * Used to prevent the premature generation of previews
164 * and by the citation inset.
166 bool file_fully_loaded;
169 mutable TocBackend toc_backend;
172 typedef pair<DocIterator, MacroData> ScopeMacro;
173 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
174 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
175 /// map from the macro name to the position map,
176 /// which maps the macro definition position to the scope and the MacroData.
177 NamePositionScopeMacroMap macros;
180 /// positions of child buffers in the buffer
181 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
182 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
183 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
184 /// position of children buffers in this buffer
185 BufferPositionMap children_positions;
186 /// map from children inclusion positions to their scope and their buffer
187 PositionScopeBufferMap position_to_children;
189 /// Container for all sort of Buffer dependant errors.
190 map<string, ErrorList> errorLists;
192 /// timestamp and checksum used to test if the file has been externally
193 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
195 unsigned long checksum_;
198 frontend::WorkAreaManager * wa_;
203 /// A cache for the bibfiles (including bibfiles of loaded child
204 /// documents), needed for appropriate update of natbib labels.
205 mutable support::FileNameList bibfilesCache_;
207 /// A cache for bibliography info
208 mutable BiblioInfo bibinfo_;
210 mutable RefCache ref_cache_;
212 /// our Text that should be wrapped in an InsetText
217 /// Creates the per buffer temporary directory
218 static FileName createBufferTmpDir()
221 // We are in our own directory. Why bother to mangle name?
222 // In fact I wrote this code to circumvent a problematic behaviour
223 // (bug?) of EMX mkstemp().
224 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
225 convert<string>(count++));
227 if (!tmpfl.createDirectory(0777)) {
228 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
229 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
230 from_utf8(tmpfl.absFilename())));
236 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
237 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
238 read_only(readonly_), filename(file), file_fully_loaded(false),
239 toc_backend(&parent), macro_lock(false), timestamp_(0),
240 checksum_(0), wa_(0), undo_(parent)
242 temppath = createBufferTmpDir();
243 lyxvc.setBuffer(&parent);
245 wa_ = new frontend::WorkAreaManager;
249 Buffer::Buffer(string const & file, bool readonly)
250 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
252 LYXERR(Debug::INFO, "Buffer::Buffer()");
254 d->inset.setBuffer(*this);
255 d->inset.initParagraphs(*this);
256 d->inset.setAutoBreakRows(true);
257 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
263 LYXERR(Debug::INFO, "Buffer::~Buffer()");
264 // here the buffer should take care that it is
265 // saved properly, before it goes into the void.
267 // GuiView already destroyed
270 // clear references to children in macro tables
271 d->children_positions.clear();
272 d->position_to_children.clear();
274 if (!d->temppath.destroyDirectory()) {
275 Alert::warning(_("Could not remove temporary directory"),
276 bformat(_("Could not remove the temporary directory %1$s"),
277 from_utf8(d->temppath.absFilename())));
280 // Remove any previewed LaTeX snippets associated with this buffer.
281 graphics::Previews::get().removeLoader(*this);
287 void Buffer::changed() const
294 frontend::WorkAreaManager & Buffer::workAreaManager() const
296 LASSERT(d->wa_, /**/);
301 Text & Buffer::text() const
303 return const_cast<Text &>(d->inset.text_);
307 Inset & Buffer::inset() const
309 return const_cast<InsetText &>(d->inset);
313 BufferParams & Buffer::params()
319 BufferParams const & Buffer::params() const
325 ParagraphList & Buffer::paragraphs()
327 return text().paragraphs();
331 ParagraphList const & Buffer::paragraphs() const
333 return text().paragraphs();
337 LyXVC & Buffer::lyxvc()
343 LyXVC const & Buffer::lyxvc() const
349 string const Buffer::temppath() const
351 return d->temppath.absFilename();
355 TexRow const & Buffer::texrow() const
361 TocBackend & Buffer::tocBackend() const
363 return d->toc_backend;
367 Undo & Buffer::undo()
373 string Buffer::latexName(bool const no_path) const
375 FileName latex_name = makeLatexName(d->filename);
376 return no_path ? latex_name.onlyFileName()
377 : latex_name.absFilename();
381 string Buffer::logName(LogType * type) const
383 string const filename = latexName(false);
385 if (filename.empty()) {
391 string const path = temppath();
393 FileName const fname(addName(temppath(),
394 onlyFilename(changeExtension(filename,
396 FileName const bname(
397 addName(path, onlyFilename(
398 changeExtension(filename,
399 formats.extension("literate") + ".out"))));
401 // If no Latex log or Build log is newer, show Build log
403 if (bname.exists() &&
404 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
405 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
408 return bname.absFilename();
410 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
413 return fname.absFilename();
417 void Buffer::setReadonly(bool const flag)
419 if (d->read_only != flag) {
426 void Buffer::setFileName(string const & newfile)
428 d->filename = makeAbsPath(newfile);
429 setReadonly(d->filename.isReadOnly());
434 int Buffer::readHeader(Lexer & lex)
436 int unknown_tokens = 0;
438 int begin_header_line = -1;
440 // Initialize parameters that may be/go lacking in header:
441 params().branchlist().clear();
442 params().preamble.erase();
443 params().options.erase();
444 params().float_placement.erase();
445 params().paperwidth.erase();
446 params().paperheight.erase();
447 params().leftmargin.erase();
448 params().rightmargin.erase();
449 params().topmargin.erase();
450 params().bottommargin.erase();
451 params().headheight.erase();
452 params().headsep.erase();
453 params().footskip.erase();
454 params().columnsep.erase();
455 params().listings_params.clear();
456 params().clearLayoutModules();
457 params().pdfoptions().clear();
459 for (int i = 0; i < 4; ++i) {
460 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
461 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
464 ErrorList & errorList = d->errorLists["Parse"];
473 if (token == "\\end_header")
477 if (token == "\\begin_header") {
478 begin_header_line = line;
482 LYXERR(Debug::PARSER, "Handling document header token: `"
485 string unknown = params().readToken(lex, token, d->filename.onlyPath());
486 if (!unknown.empty()) {
487 if (unknown[0] != '\\' && token == "\\textclass") {
488 Alert::warning(_("Unknown document class"),
489 bformat(_("Using the default document class, because the "
490 "class %1$s is unknown."), from_utf8(unknown)));
493 docstring const s = bformat(_("Unknown token: "
497 errorList.push_back(ErrorItem(_("Document header error"),
502 if (begin_header_line) {
503 docstring const s = _("\\begin_header is missing");
504 errorList.push_back(ErrorItem(_("Document header error"),
508 params().makeDocumentClass();
510 return unknown_tokens;
515 // changed to be public and have one parameter
516 // Returns false if "\end_document" is not read (Asger)
517 bool Buffer::readDocument(Lexer & lex)
519 ErrorList & errorList = d->errorLists["Parse"];
522 if (!lex.checkFor("\\begin_document")) {
523 docstring const s = _("\\begin_document is missing");
524 errorList.push_back(ErrorItem(_("Document header error"),
528 // we are reading in a brand new document
529 LASSERT(paragraphs().empty(), /**/);
533 if (params().outputChanges) {
534 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
535 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
536 LaTeXFeatures::isAvailable("xcolor");
538 if (!dvipost && !xcolorsoul) {
539 Alert::warning(_("Changes not shown in LaTeX output"),
540 _("Changes will not be highlighted in LaTeX output, "
541 "because neither dvipost nor xcolor/soul are installed.\n"
542 "Please install these packages or redefine "
543 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
544 } else if (!xcolorsoul) {
545 Alert::warning(_("Changes not shown in LaTeX output"),
546 _("Changes will not be highlighted in LaTeX output "
547 "when using pdflatex, because xcolor and soul are not installed.\n"
548 "Please install both packages or redefine "
549 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
554 bool const res = text().read(*this, lex, errorList, &(d->inset));
557 updateMacroInstances();
562 // needed to insert the selection
563 void Buffer::insertStringAsLines(ParagraphList & pars,
564 pit_type & pit, pos_type & pos,
565 Font const & fn, docstring const & str, bool autobreakrows)
569 // insert the string, don't insert doublespace
570 bool space_inserted = true;
571 for (docstring::const_iterator cit = str.begin();
572 cit != str.end(); ++cit) {
573 Paragraph & par = pars[pit];
575 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
576 breakParagraph(params(), pars, pit, pos,
577 par.layout().isEnvironment());
580 space_inserted = true;
584 // do not insert consecutive spaces if !free_spacing
585 } else if ((*cit == ' ' || *cit == '\t') &&
586 space_inserted && !par.isFreeSpacing()) {
588 } else if (*cit == '\t') {
589 if (!par.isFreeSpacing()) {
590 // tabs are like spaces here
591 par.insertChar(pos, ' ', font, params().trackChanges);
593 space_inserted = true;
595 const pos_type n = 8 - pos % 8;
596 for (pos_type i = 0; i < n; ++i) {
597 par.insertChar(pos, ' ', font, params().trackChanges);
600 space_inserted = true;
602 } else if (!isPrintable(*cit)) {
603 // Ignore unprintables
606 // just insert the character
607 par.insertChar(pos, *cit, font, params().trackChanges);
609 space_inserted = (*cit == ' ');
616 bool Buffer::readString(string const & s)
618 params().compressed = false;
620 // remove dummy empty par
621 paragraphs().clear();
625 FileName const name = FileName::tempName();
626 switch (readFile(lex, name, true)) {
630 // We need to call lyx2lyx, so write the input to a file
631 ofstream os(name.toFilesystemEncoding().c_str());
634 return readFile(name);
644 bool Buffer::readFile(FileName const & filename)
646 FileName fname(filename);
648 // remove dummy empty par
649 paragraphs().clear();
652 if (readFile(lex, fname) != success)
659 bool Buffer::isFullyLoaded() const
661 return d->file_fully_loaded;
665 void Buffer::setFullyLoaded(bool value)
667 d->file_fully_loaded = value;
671 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
674 LASSERT(!filename.empty(), /**/);
676 // the first (non-comment) token _must_ be...
677 if (!lex.checkFor("\\lyxformat")) {
678 Alert::error(_("Document format failure"),
679 bformat(_("%1$s is not a readable LyX document."),
680 from_utf8(filename.absFilename())));
686 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
687 // if present remove ".," from string.
688 size_t dot = tmp_format.find_first_of(".,");
689 //lyxerr << " dot found at " << dot << endl;
690 if (dot != string::npos)
691 tmp_format.erase(dot, 1);
692 int const file_format = convert<int>(tmp_format);
693 //lyxerr << "format: " << file_format << endl;
695 // save timestamp and checksum of the original disk file, making sure
696 // to not overwrite them with those of the file created in the tempdir
697 // when it has to be converted to the current format.
699 // Save the timestamp and checksum of disk file. If filename is an
700 // emergency file, save the timestamp and checksum of the original lyx file
701 // because isExternallyModified will check for this file. (BUG4193)
702 string diskfile = filename.absFilename();
703 if (suffixIs(diskfile, ".emergency"))
704 diskfile = diskfile.substr(0, diskfile.size() - 10);
705 saveCheckSum(FileName(diskfile));
708 if (file_format != LYX_FORMAT) {
711 // lyx2lyx would fail
714 FileName const tmpfile = FileName::tempName();
715 if (tmpfile.empty()) {
716 Alert::error(_("Conversion failed"),
717 bformat(_("%1$s is from a different"
718 " version of LyX, but a temporary"
719 " file for converting it could"
721 from_utf8(filename.absFilename())));
724 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
725 if (lyx2lyx.empty()) {
726 Alert::error(_("Conversion script not found"),
727 bformat(_("%1$s is from a different"
728 " version of LyX, but the"
729 " conversion script lyx2lyx"
730 " could not be found."),
731 from_utf8(filename.absFilename())));
734 ostringstream command;
735 command << os::python()
736 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
737 << " -t " << convert<string>(LYX_FORMAT)
738 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
739 << ' ' << quoteName(filename.toFilesystemEncoding());
740 string const command_str = command.str();
742 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
744 cmd_ret const ret = runCommand(command_str);
745 if (ret.first != 0) {
746 Alert::error(_("Conversion script failed"),
747 bformat(_("%1$s is from a different version"
748 " of LyX, but the lyx2lyx script"
749 " failed to convert it."),
750 from_utf8(filename.absFilename())));
753 bool const ret = readFile(tmpfile);
754 // Do stuff with tmpfile name and buffer name here.
755 return ret ? success : failure;
760 if (readDocument(lex)) {
761 Alert::error(_("Document format failure"),
762 bformat(_("%1$s ended unexpectedly, which means"
763 " that it is probably corrupted."),
764 from_utf8(filename.absFilename())));
767 d->file_fully_loaded = true;
772 // Should probably be moved to somewhere else: BufferView? LyXView?
773 bool Buffer::save() const
775 // We don't need autosaves in the immediate future. (Asger)
776 resetAutosaveTimers();
778 string const encodedFilename = d->filename.toFilesystemEncoding();
781 bool madeBackup = false;
783 // make a backup if the file already exists
784 if (lyxrc.make_backup && fileName().exists()) {
785 backupName = FileName(absFileName() + '~');
786 if (!lyxrc.backupdir_path.empty()) {
787 string const mangledName =
788 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
789 backupName = FileName(addName(lyxrc.backupdir_path,
792 if (fileName().copyTo(backupName)) {
795 Alert::error(_("Backup failure"),
796 bformat(_("Cannot create backup file %1$s.\n"
797 "Please check whether the directory exists and is writeable."),
798 from_utf8(backupName.absFilename())));
799 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
803 // ask if the disk file has been externally modified (use checksum method)
804 if (fileName().exists() && isExternallyModified(checksum_method)) {
805 docstring const file = makeDisplayPath(absFileName(), 20);
806 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
807 "you want to overwrite this file?"), file);
808 int const ret = Alert::prompt(_("Overwrite modified file?"),
809 text, 1, 1, _("&Overwrite"), _("&Cancel"));
814 if (writeFile(d->filename)) {
818 // Saving failed, so backup is not backup
820 backupName.moveTo(d->filename);
826 bool Buffer::writeFile(FileName const & fname) const
828 if (d->read_only && fname == d->filename)
833 docstring const str = bformat(_("Saving document %1$s..."),
834 makeDisplayPath(fname.absFilename()));
837 if (params().compressed) {
838 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
839 retval = ofs && write(ofs);
841 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
842 retval = ofs && write(ofs);
846 message(str + _(" could not write file!"));
850 removeAutosaveFile(d->filename.absFilename());
852 saveCheckSum(d->filename);
853 message(str + _(" done."));
859 bool Buffer::write(ostream & ofs) const
862 // Use the standard "C" locale for file output.
863 ofs.imbue(locale::classic());
866 // The top of the file should not be written by params().
868 // write out a comment in the top of the file
869 ofs << "#LyX " << lyx_version
870 << " created this file. For more info see http://www.lyx.org/\n"
871 << "\\lyxformat " << LYX_FORMAT << "\n"
872 << "\\begin_document\n";
874 /// For each author, set 'used' to true if there is a change
875 /// by this author in the document; otherwise set it to 'false'.
876 AuthorList::Authors::const_iterator a_it = params().authors().begin();
877 AuthorList::Authors::const_iterator a_end = params().authors().end();
878 for (; a_it != a_end; ++a_it)
879 a_it->second.setUsed(false);
881 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
882 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
883 for ( ; it != end; ++it)
884 it->checkAuthors(params().authors());
886 // now write out the buffer parameters.
887 ofs << "\\begin_header\n";
888 params().writeFile(ofs);
889 ofs << "\\end_header\n";
892 ofs << "\n\\begin_body\n";
893 text().write(*this, ofs);
894 ofs << "\n\\end_body\n";
896 // Write marker that shows file is complete
897 ofs << "\\end_document" << endl;
899 // Shouldn't really be needed....
902 // how to check if close went ok?
903 // Following is an attempt... (BE 20001011)
905 // good() returns false if any error occured, including some
907 // bad() returns true if something bad happened in the buffer,
908 // which should include file system full errors.
913 lyxerr << "File was not closed properly." << endl;
920 bool Buffer::makeLaTeXFile(FileName const & fname,
921 string const & original_path,
922 OutputParams const & runparams,
923 bool output_preamble, bool output_body) const
925 string const encoding = runparams.encoding->iconvName();
926 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
929 try { ofs.reset(encoding); }
930 catch (iconv_codecvt_facet_exception & e) {
931 lyxerr << "Caught iconv exception: " << e.what() << endl;
932 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
933 "verify that the support software for your encoding (%1$s) is "
934 "properly installed"), from_ascii(encoding)));
937 if (!openFileWrite(ofs, fname))
940 //TexStream ts(ofs.rdbuf(), &texrow());
941 ErrorList & errorList = d->errorLists["Export"];
943 bool failed_export = false;
946 writeLaTeXSource(ofs, original_path,
947 runparams, output_preamble, output_body);
949 catch (EncodingException & e) {
950 odocstringstream ods;
951 ods.put(e.failed_char);
953 oss << "0x" << hex << e.failed_char << dec;
954 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
955 " (code point %2$s)"),
956 ods.str(), from_utf8(oss.str()));
957 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
958 "representable in the chosen encoding.\n"
959 "Changing the document encoding to utf8 could help."),
960 e.par_id, e.pos, e.pos + 1));
961 failed_export = true;
963 catch (iconv_codecvt_facet_exception & e) {
964 errorList.push_back(ErrorItem(_("iconv conversion failed"),
965 _(e.what()), -1, 0, 0));
966 failed_export = true;
968 catch (exception const & e) {
969 errorList.push_back(ErrorItem(_("conversion failed"),
970 _(e.what()), -1, 0, 0));
971 failed_export = true;
974 lyxerr << "Caught some really weird exception..." << endl;
980 failed_export = true;
981 lyxerr << "File '" << fname << "' was not closed properly." << endl;
985 return !failed_export;
989 void Buffer::writeLaTeXSource(odocstream & os,
990 string const & original_path,
991 OutputParams const & runparams_in,
992 bool const output_preamble, bool const output_body) const
994 // The child documents, if any, shall be already loaded at this point.
996 OutputParams runparams = runparams_in;
998 // validate the buffer.
999 LYXERR(Debug::LATEX, " Validating buffer...");
1000 LaTeXFeatures features(*this, params(), runparams);
1002 LYXERR(Debug::LATEX, " Buffer validation done.");
1004 // The starting paragraph of the coming rows is the
1005 // first paragraph of the document. (Asger)
1006 if (output_preamble && runparams.nice) {
1007 os << "%% LyX " << lyx_version << " created this file. "
1008 "For more info, see http://www.lyx.org/.\n"
1009 "%% Do not edit unless you really know what "
1011 d->texrow.newline();
1012 d->texrow.newline();
1014 LYXERR(Debug::INFO, "lyx document header finished");
1016 // Don't move this behind the parent_buffer=0 code below,
1017 // because then the macros will not get the right "redefinition"
1018 // flag as they don't see the parent macros which are output before.
1021 // fold macros if possible, still with parent buffer as the
1022 // macros will be put in the prefix anyway.
1023 updateMacroInstances();
1025 // There are a few differences between nice LaTeX and usual files:
1026 // usual is \batchmode and has a
1027 // special input@path to allow the including of figures
1028 // with either \input or \includegraphics (what figinsets do).
1029 // input@path is set when the actual parameter
1030 // original_path is set. This is done for usual tex-file, but not
1031 // for nice-latex-file. (Matthias 250696)
1032 // Note that input@path is only needed for something the user does
1033 // in the preamble, included .tex files or ERT, files included by
1034 // LyX work without it.
1035 if (output_preamble) {
1036 if (!runparams.nice) {
1037 // code for usual, NOT nice-latex-file
1038 os << "\\batchmode\n"; // changed
1039 // from \nonstopmode
1040 d->texrow.newline();
1042 if (!original_path.empty()) {
1044 // We don't know the encoding of inputpath
1045 docstring const inputpath = from_utf8(latex_path(original_path));
1046 os << "\\makeatletter\n"
1047 << "\\def\\input@path{{"
1048 << inputpath << "/}}\n"
1049 << "\\makeatother\n";
1050 d->texrow.newline();
1051 d->texrow.newline();
1052 d->texrow.newline();
1055 // get parent macros (if this buffer has a parent) which will be
1056 // written at the document begin further down.
1057 MacroSet parentMacros;
1058 listParentMacros(parentMacros, features);
1060 // Write the preamble
1061 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1067 os << "\\begin{document}\n";
1068 d->texrow.newline();
1070 // output the parent macros
1071 MacroSet::iterator it = parentMacros.begin();
1072 MacroSet::iterator end = parentMacros.end();
1073 for (; it != end; ++it)
1074 (*it)->write(os, true);
1075 } // output_preamble
1077 d->texrow.start(paragraphs().begin()->id(), 0);
1079 LYXERR(Debug::INFO, "preamble finished, now the body.");
1081 // if we are doing a real file with body, even if this is the
1082 // child of some other buffer, let's cut the link here.
1083 // This happens for example if only a child document is printed.
1084 Buffer const * save_parent = 0;
1085 if (output_preamble) {
1086 save_parent = d->parent_buffer;
1087 d->parent_buffer = 0;
1091 latexParagraphs(*this, text(), os, d->texrow, runparams);
1093 // Restore the parenthood if needed
1094 if (output_preamble)
1095 d->parent_buffer = save_parent;
1097 // add this just in case after all the paragraphs
1099 d->texrow.newline();
1101 if (output_preamble) {
1102 os << "\\end{document}\n";
1103 d->texrow.newline();
1104 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1106 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1108 runparams_in.encoding = runparams.encoding;
1110 // Just to be sure. (Asger)
1111 d->texrow.newline();
1113 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1114 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1118 bool Buffer::isLatex() const
1120 return params().documentClass().outputType() == LATEX;
1124 bool Buffer::isLiterate() const
1126 return params().documentClass().outputType() == LITERATE;
1130 bool Buffer::isDocBook() const
1132 return params().documentClass().outputType() == DOCBOOK;
1136 void Buffer::makeDocBookFile(FileName const & fname,
1137 OutputParams const & runparams,
1138 bool const body_only) const
1140 LYXERR(Debug::LATEX, "makeDocBookFile...");
1143 if (!openFileWrite(ofs, fname))
1146 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1150 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1154 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1155 OutputParams const & runparams,
1156 bool const only_body) const
1158 LaTeXFeatures features(*this, params(), runparams);
1163 DocumentClass const & tclass = params().documentClass();
1164 string const top_element = tclass.latexname();
1167 if (runparams.flavor == OutputParams::XML)
1168 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1171 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1174 if (! tclass.class_header().empty())
1175 os << from_ascii(tclass.class_header());
1176 else if (runparams.flavor == OutputParams::XML)
1177 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1178 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1180 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1182 docstring preamble = from_utf8(params().preamble);
1183 if (runparams.flavor != OutputParams::XML ) {
1184 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1185 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1186 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1187 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1190 string const name = runparams.nice
1191 ? changeExtension(absFileName(), ".sgml") : fname;
1192 preamble += features.getIncludedFiles(name);
1193 preamble += features.getLyXSGMLEntities();
1195 if (!preamble.empty()) {
1196 os << "\n [ " << preamble << " ]";
1201 string top = top_element;
1203 if (runparams.flavor == OutputParams::XML)
1204 top += params().language->code();
1206 top += params().language->code().substr(0,2);
1209 if (!params().options.empty()) {
1211 top += params().options;
1214 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1215 << " file was created by LyX " << lyx_version
1216 << "\n See http://www.lyx.org/ for more information -->\n";
1218 params().documentClass().counters().reset();
1222 sgml::openTag(os, top);
1224 docbookParagraphs(paragraphs(), *this, os, runparams);
1225 sgml::closeTag(os, top_element);
1229 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1230 // Other flags: -wall -v0 -x
1231 int Buffer::runChktex()
1235 // get LaTeX-Filename
1236 FileName const path(temppath());
1237 string const name = addName(path.absFilename(), latexName());
1238 string const org_path = filePath();
1240 PathChanger p(path); // path to LaTeX file
1241 message(_("Running chktex..."));
1243 // Generate the LaTeX file if neccessary
1244 OutputParams runparams(¶ms().encoding());
1245 runparams.flavor = OutputParams::LATEX;
1246 runparams.nice = false;
1247 makeLaTeXFile(FileName(name), org_path, runparams);
1250 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1251 int const res = chktex.run(terr); // run chktex
1254 Alert::error(_("chktex failure"),
1255 _("Could not run chktex successfully."));
1256 } else if (res > 0) {
1257 ErrorList & errlist = d->errorLists["ChkTeX"];
1259 bufferErrors(terr, errlist);
1270 void Buffer::validate(LaTeXFeatures & features) const
1272 params().validate(features);
1276 for_each(paragraphs().begin(), paragraphs().end(),
1277 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1279 if (lyxerr.debugging(Debug::LATEX)) {
1280 features.showStruct();
1285 void Buffer::getLabelList(vector<docstring> & list) const
1287 // If this is a child document, use the parent's list instead.
1288 if (d->parent_buffer) {
1289 d->parent_buffer->getLabelList(list);
1294 Toc & toc = d->toc_backend.toc("label");
1295 TocIterator toc_it = toc.begin();
1296 TocIterator end = toc.end();
1297 for (; toc_it != end; ++toc_it) {
1298 if (toc_it->depth() == 0)
1299 list.push_back(toc_it->str());
1304 void Buffer::updateBibfilesCache() const
1306 // If this is a child document, use the parent's cache instead.
1307 if (d->parent_buffer) {
1308 d->parent_buffer->updateBibfilesCache();
1312 d->bibfilesCache_.clear();
1313 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1314 if (it->lyxCode() == BIBTEX_CODE) {
1315 InsetBibtex const & inset =
1316 static_cast<InsetBibtex const &>(*it);
1317 support::FileNameList const bibfiles = inset.getBibFiles();
1318 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1321 } else if (it->lyxCode() == INCLUDE_CODE) {
1322 InsetInclude & inset =
1323 static_cast<InsetInclude &>(*it);
1324 inset.updateBibfilesCache();
1325 support::FileNameList const & bibfiles =
1326 inset.getBibfilesCache(*this);
1327 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1335 support::FileNameList const & Buffer::getBibfilesCache() const
1337 // If this is a child document, use the parent's cache instead.
1338 if (d->parent_buffer)
1339 return d->parent_buffer->getBibfilesCache();
1341 // We update the cache when first used instead of at loading time.
1342 if (d->bibfilesCache_.empty())
1343 const_cast<Buffer *>(this)->updateBibfilesCache();
1345 return d->bibfilesCache_;
1349 BiblioInfo const & Buffer::masterBibInfo() const
1351 // if this is a child document and the parent is already loaded
1352 // use the parent's list instead [ale990412]
1353 Buffer const * const tmp = masterBuffer();
1356 return tmp->masterBibInfo();
1357 return localBibInfo();
1361 BiblioInfo const & Buffer::localBibInfo() const
1363 // cache the timestamp of the bibliography files.
1364 static map<FileName, time_t> bibfileStatus;
1366 support::FileNameList const & bibfilesCache = getBibfilesCache();
1367 // compare the cached timestamps with the actual ones.
1368 bool changed = false;
1369 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1370 support::FileNameList::const_iterator en = bibfilesCache.end();
1371 for (; ei != en; ++ ei) {
1372 time_t lastw = ei->lastModified();
1373 if (lastw != bibfileStatus[*ei]) {
1375 bibfileStatus[*ei] = lastw;
1381 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1382 it->fillWithBibKeys(d->bibinfo_, it);
1388 bool Buffer::isDepClean(string const & name) const
1390 DepClean::const_iterator const it = d->dep_clean.find(name);
1391 if (it == d->dep_clean.end())
1397 void Buffer::markDepClean(string const & name)
1399 d->dep_clean[name] = true;
1403 bool Buffer::dispatch(string const & command, bool * result)
1405 return dispatch(lyxaction.lookupFunc(command), result);
1409 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1411 bool dispatched = true;
1413 switch (func.action) {
1414 case LFUN_BUFFER_EXPORT: {
1415 bool const tmp = doExport(to_utf8(func.argument()), false);
1428 void Buffer::changeLanguage(Language const * from, Language const * to)
1430 LASSERT(from, /**/);
1433 for_each(par_iterator_begin(),
1435 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1439 bool Buffer::isMultiLingual() const
1441 ParConstIterator end = par_iterator_end();
1442 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1443 if (it->isMultiLingual(params()))
1450 DocIterator Buffer::getParFromID(int const id) const
1453 // John says this is called with id == -1 from undo
1454 lyxerr << "getParFromID(), id: " << id << endl;
1455 return doc_iterator_end(inset());
1458 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1459 if (it.paragraph().id() == id)
1462 return doc_iterator_end(inset());
1466 bool Buffer::hasParWithID(int const id) const
1468 return !getParFromID(id).atEnd();
1472 ParIterator Buffer::par_iterator_begin()
1474 return ParIterator(doc_iterator_begin(inset()));
1478 ParIterator Buffer::par_iterator_end()
1480 return ParIterator(doc_iterator_end(inset()));
1484 ParConstIterator Buffer::par_iterator_begin() const
1486 return lyx::par_const_iterator_begin(inset());
1490 ParConstIterator Buffer::par_iterator_end() const
1492 return lyx::par_const_iterator_end(inset());
1496 Language const * Buffer::language() const
1498 return params().language;
1502 docstring const Buffer::B_(string const & l10n) const
1504 return params().B_(l10n);
1508 bool Buffer::isClean() const
1510 return d->lyx_clean;
1514 bool Buffer::isBakClean() const
1516 return d->bak_clean;
1520 bool Buffer::isExternallyModified(CheckMethod method) const
1522 LASSERT(d->filename.exists(), /**/);
1523 // if method == timestamp, check timestamp before checksum
1524 return (method == checksum_method
1525 || d->timestamp_ != d->filename.lastModified())
1526 && d->checksum_ != d->filename.checksum();
1530 void Buffer::saveCheckSum(FileName const & file) const
1532 if (file.exists()) {
1533 d->timestamp_ = file.lastModified();
1534 d->checksum_ = file.checksum();
1536 // in the case of save to a new file.
1543 void Buffer::markClean() const
1545 if (!d->lyx_clean) {
1546 d->lyx_clean = true;
1549 // if the .lyx file has been saved, we don't need an
1551 d->bak_clean = true;
1555 void Buffer::markBakClean() const
1557 d->bak_clean = true;
1561 void Buffer::setUnnamed(bool flag)
1567 bool Buffer::isUnnamed() const
1573 // FIXME: this function should be moved to buffer_pimpl.C
1574 void Buffer::markDirty()
1577 d->lyx_clean = false;
1580 d->bak_clean = false;
1582 DepClean::iterator it = d->dep_clean.begin();
1583 DepClean::const_iterator const end = d->dep_clean.end();
1585 for (; it != end; ++it)
1590 FileName Buffer::fileName() const
1596 string Buffer::absFileName() const
1598 return d->filename.absFilename();
1602 string Buffer::filePath() const
1604 return d->filename.onlyPath().absFilename() + "/";
1608 bool Buffer::isReadonly() const
1610 return d->read_only;
1614 void Buffer::setParent(Buffer const * buffer)
1616 // Avoids recursive include.
1617 d->parent_buffer = buffer == this ? 0 : buffer;
1622 Buffer const * Buffer::parent()
1624 return d->parent_buffer;
1628 Buffer const * Buffer::masterBuffer() const
1630 if (!d->parent_buffer)
1633 return d->parent_buffer->masterBuffer();
1637 template<typename M>
1638 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1643 typename M::iterator it = m.lower_bound(x);
1644 if (it == m.begin())
1652 MacroData const * Buffer::getBufferMacro(docstring const & name,
1653 DocIterator const & pos) const
1655 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1657 // if paragraphs have no macro context set, pos will be empty
1661 // we haven't found anything yet
1662 DocIterator bestPos = par_iterator_begin();
1663 MacroData const * bestData = 0;
1665 // find macro definitions for name
1666 Impl::NamePositionScopeMacroMap::iterator nameIt
1667 = d->macros.find(name);
1668 if (nameIt != d->macros.end()) {
1669 // find last definition in front of pos or at pos itself
1670 Impl::PositionScopeMacroMap::const_iterator it
1671 = greatest_below(nameIt->second, pos);
1672 if (it != nameIt->second.end()) {
1674 // scope ends behind pos?
1675 if (pos < it->second.first) {
1676 // Looks good, remember this. If there
1677 // is no external macro behind this,
1678 // we found the right one already.
1679 bestPos = it->first;
1680 bestData = &it->second.second;
1684 // try previous macro if there is one
1685 if (it == nameIt->second.begin())
1692 // find macros in included files
1693 Impl::PositionScopeBufferMap::const_iterator it
1694 = greatest_below(d->position_to_children, pos);
1695 if (it == d->position_to_children.end())
1696 // no children before
1700 // do we know something better (i.e. later) already?
1701 if (it->first < bestPos )
1704 // scope ends behind pos?
1705 if (pos < it->second.first) {
1706 // look for macro in external file
1707 d->macro_lock = true;
1708 MacroData const * data
1709 = it->second.second->getMacro(name, false);
1710 d->macro_lock = false;
1712 bestPos = it->first;
1718 // try previous file if there is one
1719 if (it == d->position_to_children.begin())
1724 // return the best macro we have found
1729 MacroData const * Buffer::getMacro(docstring const & name,
1730 DocIterator const & pos, bool global) const
1735 // query buffer macros
1736 MacroData const * data = getBufferMacro(name, pos);
1740 // If there is a master buffer, query that
1741 if (d->parent_buffer) {
1742 d->macro_lock = true;
1743 MacroData const * macro = d->parent_buffer->getMacro(
1744 name, *this, false);
1745 d->macro_lock = false;
1751 data = MacroTable::globalMacros().get(name);
1760 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1762 // set scope end behind the last paragraph
1763 DocIterator scope = par_iterator_begin();
1764 scope.pit() = scope.lastpit() + 1;
1766 return getMacro(name, scope, global);
1770 MacroData const * Buffer::getMacro(docstring const & name,
1771 Buffer const & child, bool global) const
1773 // look where the child buffer is included first
1774 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1775 if (it == d->children_positions.end())
1778 // check for macros at the inclusion position
1779 return getMacro(name, it->second, global);
1783 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1785 pit_type lastpit = it.lastpit();
1787 // look for macros in each paragraph
1788 while (it.pit() <= lastpit) {
1789 Paragraph & par = it.paragraph();
1791 // iterate over the insets of the current paragraph
1792 InsetList const & insets = par.insetList();
1793 InsetList::const_iterator iit = insets.begin();
1794 InsetList::const_iterator end = insets.end();
1795 for (; iit != end; ++iit) {
1796 it.pos() = iit->pos;
1798 // is it a nested text inset?
1799 if (iit->inset->asInsetText()) {
1800 // Inset needs its own scope?
1801 InsetText const * itext
1802 = iit->inset->asInsetText();
1803 bool newScope = itext->isMacroScope();
1805 // scope which ends just behind the inset
1806 DocIterator insetScope = it;
1809 // collect macros in inset
1810 it.push_back(CursorSlice(*iit->inset));
1811 updateMacros(it, newScope ? insetScope : scope);
1816 // is it an external file?
1817 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1818 // get buffer of external file
1819 InsetCommand const & inset
1820 = static_cast<InsetCommand const &>(*iit->inset);
1821 InsetCommandParams const & ip = inset.params();
1822 d->macro_lock = true;
1823 Buffer * child = loadIfNeeded(*this, ip);
1824 d->macro_lock = false;
1828 // register its position, but only when it is
1829 // included first in the buffer
1830 if (d->children_positions.find(child)
1831 == d->children_positions.end())
1832 d->children_positions[child] = it;
1834 // register child with its scope
1835 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1839 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1843 MathMacroTemplate & macroTemplate
1844 = static_cast<MathMacroTemplate &>(*iit->inset);
1845 MacroContext mc(*this, it);
1846 macroTemplate.updateToContext(mc);
1849 bool valid = macroTemplate.validMacro();
1850 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1851 // then the BufferView's cursor will be invalid in
1852 // some cases which leads to crashes.
1857 d->macros[macroTemplate.name()][it] =
1858 Impl::ScopeMacro(scope, MacroData(*this, it));
1868 void Buffer::updateMacros() const
1873 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1875 // start with empty table
1877 d->children_positions.clear();
1878 d->position_to_children.clear();
1880 // Iterate over buffer, starting with first paragraph
1881 // The scope must be bigger than any lookup DocIterator
1882 // later. For the global lookup, lastpit+1 is used, hence
1883 // we use lastpit+2 here.
1884 DocIterator it = par_iterator_begin();
1885 DocIterator outerScope = it;
1886 outerScope.pit() = outerScope.lastpit() + 2;
1887 updateMacros(it, outerScope);
1891 void Buffer::updateMacroInstances() const
1893 LYXERR(Debug::MACROS, "updateMacroInstances for "
1894 << d->filename.onlyFileName());
1895 DocIterator it = doc_iterator_begin(inset());
1896 DocIterator end = doc_iterator_end(inset());
1897 for (; it != end; it.forwardPos()) {
1898 // look for MathData cells in InsetMathNest insets
1899 Inset * inset = it.nextInset();
1903 InsetMath * minset = inset->asInsetMath();
1907 // update macro in all cells of the InsetMathNest
1908 DocIterator::idx_type n = minset->nargs();
1909 MacroContext mc = MacroContext(*this, it);
1910 for (DocIterator::idx_type i = 0; i < n; ++i) {
1911 MathData & data = minset->cell(i);
1912 data.updateMacros(0, mc);
1918 void Buffer::listMacroNames(MacroNameSet & macros) const
1923 d->macro_lock = true;
1925 // loop over macro names
1926 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1927 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1928 for (; nameIt != nameEnd; ++nameIt)
1929 macros.insert(nameIt->first);
1931 // loop over children
1932 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1933 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1934 for (; it != end; ++it)
1935 it->first->listMacroNames(macros);
1938 if (d->parent_buffer)
1939 d->parent_buffer->listMacroNames(macros);
1941 d->macro_lock = false;
1945 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
1947 if (!d->parent_buffer)
1951 d->parent_buffer->listMacroNames(names);
1954 MacroNameSet::iterator it = names.begin();
1955 MacroNameSet::iterator end = names.end();
1956 for (; it != end; ++it) {
1958 MacroData const * data =
1959 d->parent_buffer->getMacro(*it, *this, false);
1961 macros.insert(data);
1963 // we cannot access the original MathMacroTemplate anymore
1964 // here to calls validate method. So we do its work here manually.
1965 // FIXME: somehow make the template accessible here.
1966 if (data->optionals() > 0)
1967 features.require("xargs");
1973 Buffer::References & Buffer::references(docstring const & label)
1975 if (d->parent_buffer)
1976 return const_cast<Buffer *>(masterBuffer())->references(label);
1978 RefCache::iterator it = d->ref_cache_.find(label);
1979 if (it != d->ref_cache_.end())
1980 return it->second.second;
1982 static InsetLabel const * dummy_il = 0;
1983 static References const dummy_refs;
1984 it = d->ref_cache_.insert(
1985 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
1986 return it->second.second;
1990 Buffer::References const & Buffer::references(docstring const & label) const
1992 return const_cast<Buffer *>(this)->references(label);
1996 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
1998 masterBuffer()->d->ref_cache_[label].first = il;
2002 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2004 return masterBuffer()->d->ref_cache_[label].first;
2008 void Buffer::clearReferenceCache() const
2010 if (!d->parent_buffer)
2011 d->ref_cache_.clear();
2015 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2018 //FIXME: This does not work for child documents yet.
2019 LASSERT(code == CITE_CODE, /**/);
2020 // Check if the label 'from' appears more than once
2021 vector<docstring> labels;
2023 BiblioInfo const & keys = masterBibInfo();
2024 BiblioInfo::const_iterator bit = keys.begin();
2025 BiblioInfo::const_iterator bend = keys.end();
2027 for (; bit != bend; ++bit)
2029 labels.push_back(bit->first);
2032 if (count(labels.begin(), labels.end(), from) > 1)
2035 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2036 if (it->lyxCode() == code) {
2037 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2038 docstring const oldValue = inset.getParam(paramName);
2039 if (oldValue == from)
2040 inset.setParam(paramName, to);
2046 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2047 pit_type par_end, bool full_source)
2049 OutputParams runparams(¶ms().encoding());
2050 runparams.nice = true;
2051 runparams.flavor = OutputParams::LATEX;
2052 runparams.linelen = lyxrc.plaintext_linelen;
2053 // No side effect of file copying and image conversion
2054 runparams.dryrun = true;
2058 os << "% " << _("Preview source code") << "\n\n";
2059 d->texrow.newline();
2060 d->texrow.newline();
2062 writeLaTeXSource(os, filePath(), runparams, true, true);
2064 writeDocBookSource(os, absFileName(), runparams, false);
2066 runparams.par_begin = par_begin;
2067 runparams.par_end = par_end;
2068 if (par_begin + 1 == par_end) {
2070 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2074 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2075 convert<docstring>(par_begin),
2076 convert<docstring>(par_end - 1))
2079 d->texrow.newline();
2080 d->texrow.newline();
2081 // output paragraphs
2083 latexParagraphs(*this, text(), os, d->texrow, runparams);
2086 docbookParagraphs(paragraphs(), *this, os, runparams);
2091 ErrorList & Buffer::errorList(string const & type) const
2093 static ErrorList emptyErrorList;
2094 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2095 if (I == d->errorLists.end())
2096 return emptyErrorList;
2102 void Buffer::structureChanged() const
2105 gui_->structureChanged();
2109 void Buffer::errors(string const & err) const
2116 void Buffer::message(docstring const & msg) const
2123 void Buffer::setBusy(bool on) const
2130 void Buffer::setReadOnly(bool on) const
2133 d->wa_->setReadOnly(on);
2137 void Buffer::updateTitles() const
2140 d->wa_->updateTitles();
2144 void Buffer::resetAutosaveTimers() const
2147 gui_->resetAutosaveTimers();
2151 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2160 class AutoSaveBuffer : public ForkedProcess {
2163 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2164 : buffer_(buffer), fname_(fname) {}
2166 virtual boost::shared_ptr<ForkedProcess> clone() const
2168 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2173 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2174 from_utf8(fname_.absFilename())));
2175 return run(DontWait);
2179 virtual int generateChild();
2181 Buffer const & buffer_;
2186 int AutoSaveBuffer::generateChild()
2188 // tmp_ret will be located (usually) in /tmp
2189 // will that be a problem?
2190 // Note that this calls ForkedCalls::fork(), so it's
2191 // ok cross-platform.
2192 pid_t const pid = fork();
2193 // If you want to debug the autosave
2194 // you should set pid to -1, and comment out the fork.
2195 if (pid != 0 && pid != -1)
2198 // pid = -1 signifies that lyx was unable
2199 // to fork. But we will do the save
2201 bool failed = false;
2202 FileName const tmp_ret = FileName::tempName("lyxauto");
2203 if (!tmp_ret.empty()) {
2204 buffer_.writeFile(tmp_ret);
2205 // assume successful write of tmp_ret
2206 if (!tmp_ret.moveTo(fname_))
2212 // failed to write/rename tmp_ret so try writing direct
2213 if (!buffer_.writeFile(fname_)) {
2214 // It is dangerous to do this in the child,
2215 // but safe in the parent, so...
2216 if (pid == -1) // emit message signal.
2217 buffer_.message(_("Autosave failed!"));
2221 if (pid == 0) // we are the child so...
2230 // Perfect target for a thread...
2231 void Buffer::autoSave() const
2233 if (isBakClean() || isReadonly()) {
2234 // We don't save now, but we'll try again later
2235 resetAutosaveTimers();
2239 // emit message signal.
2240 message(_("Autosaving current document..."));
2242 // create autosave filename
2243 string fname = filePath();
2245 fname += d->filename.onlyFileName();
2248 AutoSaveBuffer autosave(*this, FileName(fname));
2252 resetAutosaveTimers();
2256 string Buffer::bufferFormat() const
2266 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2267 string & result_file) const
2269 string backend_format;
2270 OutputParams runparams(¶ms().encoding());
2271 runparams.flavor = OutputParams::LATEX;
2272 runparams.linelen = lyxrc.plaintext_linelen;
2273 vector<string> backs = backends();
2274 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2275 // Get shortest path to format
2276 Graph::EdgePath path;
2277 for (vector<string>::const_iterator it = backs.begin();
2278 it != backs.end(); ++it) {
2279 Graph::EdgePath p = theConverters().getPath(*it, format);
2280 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2281 backend_format = *it;
2286 runparams.flavor = theConverters().getFlavor(path);
2288 Alert::error(_("Couldn't export file"),
2289 bformat(_("No information for exporting the format %1$s."),
2290 formats.prettyName(format)));
2294 backend_format = format;
2295 // FIXME: Don't hardcode format names here, but use a flag
2296 if (backend_format == "pdflatex")
2297 runparams.flavor = OutputParams::PDFLATEX;
2300 string filename = latexName(false);
2301 filename = addName(temppath(), filename);
2302 filename = changeExtension(filename,
2303 formats.extension(backend_format));
2306 updateMacroInstances();
2308 // Plain text backend
2309 if (backend_format == "text")
2310 writePlaintextFile(*this, FileName(filename), runparams);
2312 else if (backend_format == "lyx")
2313 writeFile(FileName(filename));
2315 else if (isDocBook()) {
2316 runparams.nice = !put_in_tempdir;
2317 makeDocBookFile(FileName(filename), runparams);
2320 else if (backend_format == format) {
2321 runparams.nice = true;
2322 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2324 } else if (!lyxrc.tex_allows_spaces
2325 && contains(filePath(), ' ')) {
2326 Alert::error(_("File name error"),
2327 _("The directory path to the document cannot contain spaces."));
2330 runparams.nice = false;
2331 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2335 string const error_type = (format == "program")
2336 ? "Build" : bufferFormat();
2337 string const ext = formats.extension(format);
2338 FileName const tmp_result_file(changeExtension(filename, ext));
2339 bool const success = theConverters().convert(this, FileName(filename),
2340 tmp_result_file, FileName(absFileName()), backend_format, format,
2341 errorList(error_type));
2342 // Emit the signal to show the error list.
2343 if (format != backend_format)
2348 if (put_in_tempdir) {
2349 result_file = tmp_result_file.absFilename();
2353 result_file = changeExtension(absFileName(), ext);
2354 // We need to copy referenced files (e. g. included graphics
2355 // if format == "dvi") to the result dir.
2356 vector<ExportedFile> const files =
2357 runparams.exportdata->externalFiles(format);
2358 string const dest = onlyPath(result_file);
2359 CopyStatus status = SUCCESS;
2360 for (vector<ExportedFile>::const_iterator it = files.begin();
2361 it != files.end() && status != CANCEL; ++it) {
2362 string const fmt = formats.getFormatFromFile(it->sourceName);
2363 status = copyFile(fmt, it->sourceName,
2364 makeAbsPath(it->exportName, dest),
2365 it->exportName, status == FORCE);
2367 if (status == CANCEL) {
2368 message(_("Document export cancelled."));
2369 } else if (tmp_result_file.exists()) {
2370 // Finally copy the main file
2371 status = copyFile(format, tmp_result_file,
2372 FileName(result_file), result_file,
2374 message(bformat(_("Document exported as %1$s "
2376 formats.prettyName(format),
2377 makeDisplayPath(result_file)));
2379 // This must be a dummy converter like fax (bug 1888)
2380 message(bformat(_("Document exported as %1$s"),
2381 formats.prettyName(format)));
2388 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2391 return doExport(format, put_in_tempdir, result_file);
2395 bool Buffer::preview(string const & format) const
2398 if (!doExport(format, true, result_file))
2400 return formats.view(*this, FileName(result_file), format);
2404 bool Buffer::isExportable(string const & format) const
2406 vector<string> backs = backends();
2407 for (vector<string>::const_iterator it = backs.begin();
2408 it != backs.end(); ++it)
2409 if (theConverters().isReachable(*it, format))
2415 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2417 vector<string> backs = backends();
2418 vector<Format const *> result =
2419 theConverters().getReachable(backs[0], only_viewable, true);
2420 for (vector<string>::const_iterator it = backs.begin() + 1;
2421 it != backs.end(); ++it) {
2422 vector<Format const *> r =
2423 theConverters().getReachable(*it, only_viewable, false);
2424 result.insert(result.end(), r.begin(), r.end());
2430 vector<string> Buffer::backends() const
2433 if (params().baseClass()->isTeXClassAvailable()) {
2434 v.push_back(bufferFormat());
2435 // FIXME: Don't hardcode format names here, but use a flag
2436 if (v.back() == "latex")
2437 v.push_back("pdflatex");
2439 v.push_back("text");
2445 bool Buffer::readFileHelper(FileName const & s)
2447 // File information about normal file
2449 docstring const file = makeDisplayPath(s.absFilename(), 50);
2450 docstring text = bformat(_("The specified document\n%1$s"
2451 "\ncould not be read."), file);
2452 Alert::error(_("Could not read document"), text);
2456 // Check if emergency save file exists and is newer.
2457 FileName const e(s.absFilename() + ".emergency");
2459 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2460 docstring const file = makeDisplayPath(s.absFilename(), 20);
2461 docstring const text =
2462 bformat(_("An emergency save of the document "
2464 "Recover emergency save?"), file);
2465 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2466 _("&Recover"), _("&Load Original"),
2470 // the file is not saved if we load the emergency file.
2480 // Now check if autosave file is newer.
2481 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2483 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2484 docstring const file = makeDisplayPath(s.absFilename(), 20);
2485 docstring const text =
2486 bformat(_("The backup of the document "
2487 "%1$s is newer.\n\nLoad the "
2488 "backup instead?"), file);
2489 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2490 _("&Load backup"), _("Load &original"),
2494 // the file is not saved if we load the autosave file.
2498 // Here we delete the autosave
2509 bool Buffer::loadLyXFile(FileName const & s)
2511 if (s.isReadableFile()) {
2512 if (readFileHelper(s)) {
2513 lyxvc().file_found_hook(s);
2514 if (!s.isWritable())
2519 docstring const file = makeDisplayPath(s.absFilename(), 20);
2520 // Here we probably should run
2521 if (LyXVC::file_not_found_hook(s)) {
2522 docstring const text =
2523 bformat(_("Do you want to retrieve the document"
2524 " %1$s from version control?"), file);
2525 int const ret = Alert::prompt(_("Retrieve from version control?"),
2526 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2529 // How can we know _how_ to do the checkout?
2530 // With the current VC support it has to be,
2531 // a RCS file since CVS do not have special ,v files.
2533 return loadLyXFile(s);
2541 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2543 TeXErrors::Errors::const_iterator cit = terr.begin();
2544 TeXErrors::Errors::const_iterator end = terr.end();
2546 for (; cit != end; ++cit) {
2549 int errorRow = cit->error_in_line;
2550 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2556 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2557 } while (found && id_start == id_end && pos_start == pos_end);
2559 errorList.push_back(ErrorItem(cit->error_desc,
2560 cit->error_text, id_start, pos_start, pos_end));