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 mutable RefCache ref_cache_;
209 /// our Text that should be wrapped in an InsetText
214 /// Creates the per buffer temporary directory
215 static FileName createBufferTmpDir()
218 // We are in our own directory. Why bother to mangle name?
219 // In fact I wrote this code to circumvent a problematic behaviour
220 // (bug?) of EMX mkstemp().
221 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
222 convert<string>(count++));
224 if (!tmpfl.createDirectory(0777)) {
225 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
226 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
227 from_utf8(tmpfl.absFilename())));
233 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
234 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
235 read_only(readonly_), filename(file), file_fully_loaded(false),
236 toc_backend(&parent), macro_lock(false),
237 timestamp_(0), checksum_(0), wa_(0), undo_(parent)
239 temppath = createBufferTmpDir();
240 lyxvc.setBuffer(&parent);
242 wa_ = new frontend::WorkAreaManager;
246 Buffer::Buffer(string const & file, bool readonly)
247 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
249 LYXERR(Debug::INFO, "Buffer::Buffer()");
251 d->inset.setBuffer(*this);
252 d->inset.initParagraphs(*this);
253 d->inset.setAutoBreakRows(true);
254 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
260 LYXERR(Debug::INFO, "Buffer::~Buffer()");
261 // here the buffer should take care that it is
262 // saved properly, before it goes into the void.
264 // GuiView already destroyed
267 // clear references to children in macro tables
268 d->children_positions.clear();
269 d->position_to_children.clear();
271 if (!d->temppath.destroyDirectory()) {
272 Alert::warning(_("Could not remove temporary directory"),
273 bformat(_("Could not remove the temporary directory %1$s"),
274 from_utf8(d->temppath.absFilename())));
277 // Remove any previewed LaTeX snippets associated with this buffer.
278 graphics::Previews::get().removeLoader(*this);
284 void Buffer::changed() const
291 frontend::WorkAreaManager & Buffer::workAreaManager() const
293 LASSERT(d->wa_, /**/);
298 Text & Buffer::text() const
300 return const_cast<Text &>(d->inset.text_);
304 Inset & Buffer::inset() const
306 return const_cast<InsetText &>(d->inset);
310 BufferParams & Buffer::params()
316 BufferParams const & Buffer::params() const
322 ParagraphList & Buffer::paragraphs()
324 return text().paragraphs();
328 ParagraphList const & Buffer::paragraphs() const
330 return text().paragraphs();
334 LyXVC & Buffer::lyxvc()
340 LyXVC const & Buffer::lyxvc() const
346 string const Buffer::temppath() const
348 return d->temppath.absFilename();
352 TexRow const & Buffer::texrow() const
358 TocBackend & Buffer::tocBackend() const
360 return d->toc_backend;
364 Undo & Buffer::undo()
370 string Buffer::latexName(bool const no_path) const
372 FileName latex_name = makeLatexName(d->filename);
373 return no_path ? latex_name.onlyFileName()
374 : latex_name.absFilename();
378 string Buffer::logName(LogType * type) const
380 string const filename = latexName(false);
382 if (filename.empty()) {
388 string const path = temppath();
390 FileName const fname(addName(temppath(),
391 onlyFilename(changeExtension(filename,
393 FileName const bname(
394 addName(path, onlyFilename(
395 changeExtension(filename,
396 formats.extension("literate") + ".out"))));
398 // If no Latex log or Build log is newer, show Build log
400 if (bname.exists() &&
401 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
402 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
405 return bname.absFilename();
407 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
410 return fname.absFilename();
414 void Buffer::setReadonly(bool const flag)
416 if (d->read_only != flag) {
423 void Buffer::setFileName(string const & newfile)
425 d->filename = makeAbsPath(newfile);
426 setReadonly(d->filename.isReadOnly());
431 int Buffer::readHeader(Lexer & lex)
433 int unknown_tokens = 0;
435 int begin_header_line = -1;
437 // Initialize parameters that may be/go lacking in header:
438 params().branchlist().clear();
439 params().preamble.erase();
440 params().options.erase();
441 params().float_placement.erase();
442 params().paperwidth.erase();
443 params().paperheight.erase();
444 params().leftmargin.erase();
445 params().rightmargin.erase();
446 params().topmargin.erase();
447 params().bottommargin.erase();
448 params().headheight.erase();
449 params().headsep.erase();
450 params().footskip.erase();
451 params().columnsep.erase();
452 params().listings_params.clear();
453 params().clearLayoutModules();
454 params().pdfoptions().clear();
456 for (int i = 0; i < 4; ++i) {
457 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
458 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
461 ErrorList & errorList = d->errorLists["Parse"];
470 if (token == "\\end_header")
474 if (token == "\\begin_header") {
475 begin_header_line = line;
479 LYXERR(Debug::PARSER, "Handling document header token: `"
482 string unknown = params().readToken(lex, token, d->filename.onlyPath());
483 if (!unknown.empty()) {
484 if (unknown[0] != '\\' && token == "\\textclass") {
485 Alert::warning(_("Unknown document class"),
486 bformat(_("Using the default document class, because the "
487 "class %1$s is unknown."), from_utf8(unknown)));
490 docstring const s = bformat(_("Unknown token: "
494 errorList.push_back(ErrorItem(_("Document header error"),
499 if (begin_header_line) {
500 docstring const s = _("\\begin_header is missing");
501 errorList.push_back(ErrorItem(_("Document header error"),
505 params().makeDocumentClass();
507 return unknown_tokens;
512 // changed to be public and have one parameter
513 // Returns false if "\end_document" is not read (Asger)
514 bool Buffer::readDocument(Lexer & lex)
516 ErrorList & errorList = d->errorLists["Parse"];
519 if (!lex.checkFor("\\begin_document")) {
520 docstring const s = _("\\begin_document is missing");
521 errorList.push_back(ErrorItem(_("Document header error"),
525 // we are reading in a brand new document
526 LASSERT(paragraphs().empty(), /**/);
530 if (params().outputChanges) {
531 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
532 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
533 LaTeXFeatures::isAvailable("xcolor");
535 if (!dvipost && !xcolorsoul) {
536 Alert::warning(_("Changes not shown in LaTeX output"),
537 _("Changes will not be highlighted in LaTeX output, "
538 "because neither dvipost nor xcolor/soul are installed.\n"
539 "Please install these packages or redefine "
540 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
541 } else if (!xcolorsoul) {
542 Alert::warning(_("Changes not shown in LaTeX output"),
543 _("Changes will not be highlighted in LaTeX output "
544 "when using pdflatex, because xcolor and soul are not installed.\n"
545 "Please install both packages or redefine "
546 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
551 bool const res = text().read(*this, lex, errorList, &(d->inset));
554 updateMacroInstances();
559 // needed to insert the selection
560 void Buffer::insertStringAsLines(ParagraphList & pars,
561 pit_type & pit, pos_type & pos,
562 Font const & fn, docstring const & str, bool autobreakrows)
566 // insert the string, don't insert doublespace
567 bool space_inserted = true;
568 for (docstring::const_iterator cit = str.begin();
569 cit != str.end(); ++cit) {
570 Paragraph & par = pars[pit];
572 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
573 breakParagraph(params(), pars, pit, pos,
574 par.layout().isEnvironment());
577 space_inserted = true;
581 // do not insert consecutive spaces if !free_spacing
582 } else if ((*cit == ' ' || *cit == '\t') &&
583 space_inserted && !par.isFreeSpacing()) {
585 } else if (*cit == '\t') {
586 if (!par.isFreeSpacing()) {
587 // tabs are like spaces here
588 par.insertChar(pos, ' ', font, params().trackChanges);
590 space_inserted = true;
592 const pos_type n = 8 - pos % 8;
593 for (pos_type i = 0; i < n; ++i) {
594 par.insertChar(pos, ' ', font, params().trackChanges);
597 space_inserted = true;
599 } else if (!isPrintable(*cit)) {
600 // Ignore unprintables
603 // just insert the character
604 par.insertChar(pos, *cit, font, params().trackChanges);
606 space_inserted = (*cit == ' ');
613 bool Buffer::readString(string const & s)
615 params().compressed = false;
617 // remove dummy empty par
618 paragraphs().clear();
622 FileName const name = FileName::tempName();
623 switch (readFile(lex, name, true)) {
627 // We need to call lyx2lyx, so write the input to a file
628 ofstream os(name.toFilesystemEncoding().c_str());
631 return readFile(name);
641 bool Buffer::readFile(FileName const & filename)
643 FileName fname(filename);
645 // remove dummy empty par
646 paragraphs().clear();
649 if (readFile(lex, fname) != success)
656 bool Buffer::isFullyLoaded() const
658 return d->file_fully_loaded;
662 void Buffer::setFullyLoaded(bool value)
664 d->file_fully_loaded = value;
668 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
671 LASSERT(!filename.empty(), /**/);
673 // the first (non-comment) token _must_ be...
674 if (!lex.checkFor("\\lyxformat")) {
675 Alert::error(_("Document format failure"),
676 bformat(_("%1$s is not a readable LyX document."),
677 from_utf8(filename.absFilename())));
683 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
684 // if present remove ".," from string.
685 size_t dot = tmp_format.find_first_of(".,");
686 //lyxerr << " dot found at " << dot << endl;
687 if (dot != string::npos)
688 tmp_format.erase(dot, 1);
689 int const file_format = convert<int>(tmp_format);
690 //lyxerr << "format: " << file_format << endl;
692 // save timestamp and checksum of the original disk file, making sure
693 // to not overwrite them with those of the file created in the tempdir
694 // when it has to be converted to the current format.
696 // Save the timestamp and checksum of disk file. If filename is an
697 // emergency file, save the timestamp and checksum of the original lyx file
698 // because isExternallyModified will check for this file. (BUG4193)
699 string diskfile = filename.absFilename();
700 if (suffixIs(diskfile, ".emergency"))
701 diskfile = diskfile.substr(0, diskfile.size() - 10);
702 saveCheckSum(FileName(diskfile));
705 if (file_format != LYX_FORMAT) {
708 // lyx2lyx would fail
711 FileName const tmpfile = FileName::tempName();
712 if (tmpfile.empty()) {
713 Alert::error(_("Conversion failed"),
714 bformat(_("%1$s is from a different"
715 " version of LyX, but a temporary"
716 " file for converting it could"
718 from_utf8(filename.absFilename())));
721 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
722 if (lyx2lyx.empty()) {
723 Alert::error(_("Conversion script not found"),
724 bformat(_("%1$s is from a different"
725 " version of LyX, but the"
726 " conversion script lyx2lyx"
727 " could not be found."),
728 from_utf8(filename.absFilename())));
731 ostringstream command;
732 command << os::python()
733 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
734 << " -t " << convert<string>(LYX_FORMAT)
735 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
736 << ' ' << quoteName(filename.toFilesystemEncoding());
737 string const command_str = command.str();
739 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
741 cmd_ret const ret = runCommand(command_str);
742 if (ret.first != 0) {
743 Alert::error(_("Conversion script failed"),
744 bformat(_("%1$s is from a different version"
745 " of LyX, but the lyx2lyx script"
746 " failed to convert it."),
747 from_utf8(filename.absFilename())));
750 bool const ret = readFile(tmpfile);
751 // Do stuff with tmpfile name and buffer name here.
752 return ret ? success : failure;
757 if (readDocument(lex)) {
758 Alert::error(_("Document format failure"),
759 bformat(_("%1$s ended unexpectedly, which means"
760 " that it is probably corrupted."),
761 from_utf8(filename.absFilename())));
764 d->file_fully_loaded = true;
769 // Should probably be moved to somewhere else: BufferView? LyXView?
770 bool Buffer::save() const
772 // We don't need autosaves in the immediate future. (Asger)
773 resetAutosaveTimers();
775 string const encodedFilename = d->filename.toFilesystemEncoding();
778 bool madeBackup = false;
780 // make a backup if the file already exists
781 if (lyxrc.make_backup && fileName().exists()) {
782 backupName = FileName(absFileName() + '~');
783 if (!lyxrc.backupdir_path.empty()) {
784 string const mangledName =
785 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
786 backupName = FileName(addName(lyxrc.backupdir_path,
789 if (fileName().copyTo(backupName)) {
792 Alert::error(_("Backup failure"),
793 bformat(_("Cannot create backup file %1$s.\n"
794 "Please check whether the directory exists and is writeable."),
795 from_utf8(backupName.absFilename())));
796 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
800 // ask if the disk file has been externally modified (use checksum method)
801 if (fileName().exists() && isExternallyModified(checksum_method)) {
802 docstring const file = makeDisplayPath(absFileName(), 20);
803 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
804 "you want to overwrite this file?"), file);
805 int const ret = Alert::prompt(_("Overwrite modified file?"),
806 text, 1, 1, _("&Overwrite"), _("&Cancel"));
811 if (writeFile(d->filename)) {
815 // Saving failed, so backup is not backup
817 backupName.moveTo(d->filename);
823 bool Buffer::writeFile(FileName const & fname) const
825 if (d->read_only && fname == d->filename)
830 docstring const str = bformat(_("Saving document %1$s..."),
831 makeDisplayPath(fname.absFilename()));
834 if (params().compressed) {
835 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
836 retval = ofs && write(ofs);
838 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
839 retval = ofs && write(ofs);
843 message(str + _(" could not write file!"));
847 removeAutosaveFile(d->filename.absFilename());
849 saveCheckSum(d->filename);
850 message(str + _(" done."));
856 bool Buffer::write(ostream & ofs) const
859 // Use the standard "C" locale for file output.
860 ofs.imbue(locale::classic());
863 // The top of the file should not be written by params().
865 // write out a comment in the top of the file
866 ofs << "#LyX " << lyx_version
867 << " created this file. For more info see http://www.lyx.org/\n"
868 << "\\lyxformat " << LYX_FORMAT << "\n"
869 << "\\begin_document\n";
871 /// For each author, set 'used' to true if there is a change
872 /// by this author in the document; otherwise set it to 'false'.
873 AuthorList::Authors::const_iterator a_it = params().authors().begin();
874 AuthorList::Authors::const_iterator a_end = params().authors().end();
875 for (; a_it != a_end; ++a_it)
876 a_it->second.setUsed(false);
878 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
879 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
880 for ( ; it != end; ++it)
881 it->checkAuthors(params().authors());
883 // now write out the buffer parameters.
884 ofs << "\\begin_header\n";
885 params().writeFile(ofs);
886 ofs << "\\end_header\n";
889 ofs << "\n\\begin_body\n";
890 text().write(*this, ofs);
891 ofs << "\n\\end_body\n";
893 // Write marker that shows file is complete
894 ofs << "\\end_document" << endl;
896 // Shouldn't really be needed....
899 // how to check if close went ok?
900 // Following is an attempt... (BE 20001011)
902 // good() returns false if any error occured, including some
904 // bad() returns true if something bad happened in the buffer,
905 // which should include file system full errors.
910 lyxerr << "File was not closed properly." << endl;
917 bool Buffer::makeLaTeXFile(FileName const & fname,
918 string const & original_path,
919 OutputParams const & runparams,
920 bool output_preamble, bool output_body) const
922 string const encoding = runparams.encoding->iconvName();
923 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
926 try { ofs.reset(encoding); }
927 catch (iconv_codecvt_facet_exception & e) {
928 lyxerr << "Caught iconv exception: " << e.what() << endl;
929 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
930 "verify that the support software for your encoding (%1$s) is "
931 "properly installed"), from_ascii(encoding)));
934 if (!openFileWrite(ofs, fname))
937 //TexStream ts(ofs.rdbuf(), &texrow());
938 ErrorList & errorList = d->errorLists["Export"];
940 bool failed_export = false;
943 writeLaTeXSource(ofs, original_path,
944 runparams, output_preamble, output_body);
946 catch (EncodingException & e) {
947 odocstringstream ods;
948 ods.put(e.failed_char);
950 oss << "0x" << hex << e.failed_char << dec;
951 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
952 " (code point %2$s)"),
953 ods.str(), from_utf8(oss.str()));
954 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
955 "representable in the chosen encoding.\n"
956 "Changing the document encoding to utf8 could help."),
957 e.par_id, e.pos, e.pos + 1));
958 failed_export = true;
960 catch (iconv_codecvt_facet_exception & e) {
961 errorList.push_back(ErrorItem(_("iconv conversion failed"),
962 _(e.what()), -1, 0, 0));
963 failed_export = true;
965 catch (exception const & e) {
966 errorList.push_back(ErrorItem(_("conversion failed"),
967 _(e.what()), -1, 0, 0));
968 failed_export = true;
971 lyxerr << "Caught some really weird exception..." << endl;
977 failed_export = true;
978 lyxerr << "File '" << fname << "' was not closed properly." << endl;
982 return !failed_export;
986 void Buffer::writeLaTeXSource(odocstream & os,
987 string const & original_path,
988 OutputParams const & runparams_in,
989 bool const output_preamble, bool const output_body) const
991 // The child documents, if any, shall be already loaded at this point.
993 OutputParams runparams = runparams_in;
995 // validate the buffer.
996 LYXERR(Debug::LATEX, " Validating buffer...");
997 LaTeXFeatures features(*this, params(), runparams);
999 LYXERR(Debug::LATEX, " Buffer validation done.");
1001 // The starting paragraph of the coming rows is the
1002 // first paragraph of the document. (Asger)
1003 if (output_preamble && runparams.nice) {
1004 os << "%% LyX " << lyx_version << " created this file. "
1005 "For more info, see http://www.lyx.org/.\n"
1006 "%% Do not edit unless you really know what "
1008 d->texrow.newline();
1009 d->texrow.newline();
1011 LYXERR(Debug::INFO, "lyx document header finished");
1013 // Don't move this behind the parent_buffer=0 code below,
1014 // because then the macros will not get the right "redefinition"
1015 // flag as they don't see the parent macros which are output before.
1018 // fold macros if possible, still with parent buffer as the
1019 // macros will be put in the prefix anyway.
1020 updateMacroInstances();
1022 // There are a few differences between nice LaTeX and usual files:
1023 // usual is \batchmode and has a
1024 // special input@path to allow the including of figures
1025 // with either \input or \includegraphics (what figinsets do).
1026 // input@path is set when the actual parameter
1027 // original_path is set. This is done for usual tex-file, but not
1028 // for nice-latex-file. (Matthias 250696)
1029 // Note that input@path is only needed for something the user does
1030 // in the preamble, included .tex files or ERT, files included by
1031 // LyX work without it.
1032 if (output_preamble) {
1033 if (!runparams.nice) {
1034 // code for usual, NOT nice-latex-file
1035 os << "\\batchmode\n"; // changed
1036 // from \nonstopmode
1037 d->texrow.newline();
1039 if (!original_path.empty()) {
1041 // We don't know the encoding of inputpath
1042 docstring const inputpath = from_utf8(latex_path(original_path));
1043 os << "\\makeatletter\n"
1044 << "\\def\\input@path{{"
1045 << inputpath << "/}}\n"
1046 << "\\makeatother\n";
1047 d->texrow.newline();
1048 d->texrow.newline();
1049 d->texrow.newline();
1052 // get parent macros (if this buffer has a parent) which will be
1053 // written at the document begin further down.
1054 MacroSet parentMacros;
1055 listParentMacros(parentMacros, features);
1057 // Write the preamble
1058 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1064 os << "\\begin{document}\n";
1065 d->texrow.newline();
1067 // output the parent macros
1068 MacroSet::iterator it = parentMacros.begin();
1069 MacroSet::iterator end = parentMacros.end();
1070 for (; it != end; ++it)
1071 (*it)->write(os, true);
1072 } // output_preamble
1074 d->texrow.start(paragraphs().begin()->id(), 0);
1076 LYXERR(Debug::INFO, "preamble finished, now the body.");
1078 // if we are doing a real file with body, even if this is the
1079 // child of some other buffer, let's cut the link here.
1080 // This happens for example if only a child document is printed.
1081 Buffer const * save_parent = 0;
1082 if (output_preamble) {
1083 save_parent = d->parent_buffer;
1084 d->parent_buffer = 0;
1088 latexParagraphs(*this, text(), os, d->texrow, runparams);
1090 // Restore the parenthood if needed
1091 if (output_preamble)
1092 d->parent_buffer = save_parent;
1094 // add this just in case after all the paragraphs
1096 d->texrow.newline();
1098 if (output_preamble) {
1099 os << "\\end{document}\n";
1100 d->texrow.newline();
1101 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1103 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1105 runparams_in.encoding = runparams.encoding;
1107 // Just to be sure. (Asger)
1108 d->texrow.newline();
1110 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1111 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1115 bool Buffer::isLatex() const
1117 return params().documentClass().outputType() == LATEX;
1121 bool Buffer::isLiterate() const
1123 return params().documentClass().outputType() == LITERATE;
1127 bool Buffer::isDocBook() const
1129 return params().documentClass().outputType() == DOCBOOK;
1133 void Buffer::makeDocBookFile(FileName const & fname,
1134 OutputParams const & runparams,
1135 bool const body_only) const
1137 LYXERR(Debug::LATEX, "makeDocBookFile...");
1140 if (!openFileWrite(ofs, fname))
1143 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1147 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1151 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1152 OutputParams const & runparams,
1153 bool const only_body) const
1155 LaTeXFeatures features(*this, params(), runparams);
1160 DocumentClass const & tclass = params().documentClass();
1161 string const top_element = tclass.latexname();
1164 if (runparams.flavor == OutputParams::XML)
1165 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1168 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1171 if (! tclass.class_header().empty())
1172 os << from_ascii(tclass.class_header());
1173 else if (runparams.flavor == OutputParams::XML)
1174 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1175 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1177 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1179 docstring preamble = from_utf8(params().preamble);
1180 if (runparams.flavor != OutputParams::XML ) {
1181 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1182 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1183 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1184 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1187 string const name = runparams.nice
1188 ? changeExtension(absFileName(), ".sgml") : fname;
1189 preamble += features.getIncludedFiles(name);
1190 preamble += features.getLyXSGMLEntities();
1192 if (!preamble.empty()) {
1193 os << "\n [ " << preamble << " ]";
1198 string top = top_element;
1200 if (runparams.flavor == OutputParams::XML)
1201 top += params().language->code();
1203 top += params().language->code().substr(0,2);
1206 if (!params().options.empty()) {
1208 top += params().options;
1211 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1212 << " file was created by LyX " << lyx_version
1213 << "\n See http://www.lyx.org/ for more information -->\n";
1215 params().documentClass().counters().reset();
1219 sgml::openTag(os, top);
1221 docbookParagraphs(paragraphs(), *this, os, runparams);
1222 sgml::closeTag(os, top_element);
1226 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1227 // Other flags: -wall -v0 -x
1228 int Buffer::runChktex()
1232 // get LaTeX-Filename
1233 FileName const path(temppath());
1234 string const name = addName(path.absFilename(), latexName());
1235 string const org_path = filePath();
1237 PathChanger p(path); // path to LaTeX file
1238 message(_("Running chktex..."));
1240 // Generate the LaTeX file if neccessary
1241 OutputParams runparams(¶ms().encoding());
1242 runparams.flavor = OutputParams::LATEX;
1243 runparams.nice = false;
1244 makeLaTeXFile(FileName(name), org_path, runparams);
1247 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1248 int const res = chktex.run(terr); // run chktex
1251 Alert::error(_("chktex failure"),
1252 _("Could not run chktex successfully."));
1253 } else if (res > 0) {
1254 ErrorList & errlist = d->errorLists["ChkTeX"];
1256 bufferErrors(terr, errlist);
1267 void Buffer::validate(LaTeXFeatures & features) const
1269 params().validate(features);
1273 for_each(paragraphs().begin(), paragraphs().end(),
1274 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1276 if (lyxerr.debugging(Debug::LATEX)) {
1277 features.showStruct();
1282 void Buffer::getLabelList(vector<docstring> & list) const
1284 // If this is a child document, use the parent's list instead.
1285 if (d->parent_buffer) {
1286 d->parent_buffer->getLabelList(list);
1291 Toc & toc = d->toc_backend.toc("label");
1292 TocIterator toc_it = toc.begin();
1293 TocIterator end = toc.end();
1294 for (; toc_it != end; ++toc_it) {
1295 if (toc_it->depth() == 0)
1296 list.push_back(toc_it->str());
1301 void Buffer::updateBibfilesCache() const
1303 // If this is a child document, use the parent's cache instead.
1304 if (d->parent_buffer) {
1305 d->parent_buffer->updateBibfilesCache();
1309 d->bibfilesCache_.clear();
1310 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1311 if (it->lyxCode() == BIBTEX_CODE) {
1312 InsetBibtex const & inset =
1313 static_cast<InsetBibtex const &>(*it);
1314 support::FileNameList const bibfiles = inset.getBibFiles();
1315 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1318 } else if (it->lyxCode() == INCLUDE_CODE) {
1319 InsetInclude & inset =
1320 static_cast<InsetInclude &>(*it);
1321 inset.updateBibfilesCache();
1322 support::FileNameList const & bibfiles =
1323 inset.getBibfilesCache(*this);
1324 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1332 support::FileNameList const & Buffer::getBibfilesCache() const
1334 // If this is a child document, use the parent's cache instead.
1335 if (d->parent_buffer)
1336 return d->parent_buffer->getBibfilesCache();
1338 // We update the cache when first used instead of at loading time.
1339 if (d->bibfilesCache_.empty())
1340 const_cast<Buffer *>(this)->updateBibfilesCache();
1342 return d->bibfilesCache_;
1346 bool Buffer::isDepClean(string const & name) const
1348 DepClean::const_iterator const it = d->dep_clean.find(name);
1349 if (it == d->dep_clean.end())
1355 void Buffer::markDepClean(string const & name)
1357 d->dep_clean[name] = true;
1361 bool Buffer::dispatch(string const & command, bool * result)
1363 return dispatch(lyxaction.lookupFunc(command), result);
1367 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1369 bool dispatched = true;
1371 switch (func.action) {
1372 case LFUN_BUFFER_EXPORT: {
1373 bool const tmp = doExport(to_utf8(func.argument()), false);
1386 void Buffer::changeLanguage(Language const * from, Language const * to)
1388 LASSERT(from, /**/);
1391 for_each(par_iterator_begin(),
1393 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1397 bool Buffer::isMultiLingual() const
1399 ParConstIterator end = par_iterator_end();
1400 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1401 if (it->isMultiLingual(params()))
1408 DocIterator Buffer::getParFromID(int const id) const
1411 // John says this is called with id == -1 from undo
1412 lyxerr << "getParFromID(), id: " << id << endl;
1413 return doc_iterator_end(inset());
1416 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1417 if (it.paragraph().id() == id)
1420 return doc_iterator_end(inset());
1424 bool Buffer::hasParWithID(int const id) const
1426 return !getParFromID(id).atEnd();
1430 ParIterator Buffer::par_iterator_begin()
1432 return ParIterator(doc_iterator_begin(inset()));
1436 ParIterator Buffer::par_iterator_end()
1438 return ParIterator(doc_iterator_end(inset()));
1442 ParConstIterator Buffer::par_iterator_begin() const
1444 return lyx::par_const_iterator_begin(inset());
1448 ParConstIterator Buffer::par_iterator_end() const
1450 return lyx::par_const_iterator_end(inset());
1454 Language const * Buffer::language() const
1456 return params().language;
1460 docstring const Buffer::B_(string const & l10n) const
1462 return params().B_(l10n);
1466 bool Buffer::isClean() const
1468 return d->lyx_clean;
1472 bool Buffer::isBakClean() const
1474 return d->bak_clean;
1478 bool Buffer::isExternallyModified(CheckMethod method) const
1480 LASSERT(d->filename.exists(), /**/);
1481 // if method == timestamp, check timestamp before checksum
1482 return (method == checksum_method
1483 || d->timestamp_ != d->filename.lastModified())
1484 && d->checksum_ != d->filename.checksum();
1488 void Buffer::saveCheckSum(FileName const & file) const
1490 if (file.exists()) {
1491 d->timestamp_ = file.lastModified();
1492 d->checksum_ = file.checksum();
1494 // in the case of save to a new file.
1501 void Buffer::markClean() const
1503 if (!d->lyx_clean) {
1504 d->lyx_clean = true;
1507 // if the .lyx file has been saved, we don't need an
1509 d->bak_clean = true;
1513 void Buffer::markBakClean() const
1515 d->bak_clean = true;
1519 void Buffer::setUnnamed(bool flag)
1525 bool Buffer::isUnnamed() const
1531 // FIXME: this function should be moved to buffer_pimpl.C
1532 void Buffer::markDirty()
1535 d->lyx_clean = false;
1538 d->bak_clean = false;
1540 DepClean::iterator it = d->dep_clean.begin();
1541 DepClean::const_iterator const end = d->dep_clean.end();
1543 for (; it != end; ++it)
1548 FileName Buffer::fileName() const
1554 string Buffer::absFileName() const
1556 return d->filename.absFilename();
1560 string Buffer::filePath() const
1562 return d->filename.onlyPath().absFilename() + "/";
1566 bool Buffer::isReadonly() const
1568 return d->read_only;
1572 void Buffer::setParent(Buffer const * buffer)
1574 // Avoids recursive include.
1575 d->parent_buffer = buffer == this ? 0 : buffer;
1580 Buffer const * Buffer::parent()
1582 return d->parent_buffer;
1586 Buffer const * Buffer::masterBuffer() const
1588 if (!d->parent_buffer)
1591 return d->parent_buffer->masterBuffer();
1595 template<typename M>
1596 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1601 typename M::iterator it = m.lower_bound(x);
1602 if (it == m.begin())
1610 MacroData const * Buffer::getBufferMacro(docstring const & name,
1611 DocIterator const & pos) const
1613 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1615 // if paragraphs have no macro context set, pos will be empty
1619 // we haven't found anything yet
1620 DocIterator bestPos = par_iterator_begin();
1621 MacroData const * bestData = 0;
1623 // find macro definitions for name
1624 Impl::NamePositionScopeMacroMap::iterator nameIt
1625 = d->macros.find(name);
1626 if (nameIt != d->macros.end()) {
1627 // find last definition in front of pos or at pos itself
1628 Impl::PositionScopeMacroMap::const_iterator it
1629 = greatest_below(nameIt->second, pos);
1630 if (it != nameIt->second.end()) {
1632 // scope ends behind pos?
1633 if (pos < it->second.first) {
1634 // Looks good, remember this. If there
1635 // is no external macro behind this,
1636 // we found the right one already.
1637 bestPos = it->first;
1638 bestData = &it->second.second;
1642 // try previous macro if there is one
1643 if (it == nameIt->second.begin())
1650 // find macros in included files
1651 Impl::PositionScopeBufferMap::const_iterator it
1652 = greatest_below(d->position_to_children, pos);
1653 if (it == d->position_to_children.end())
1654 // no children before
1658 // do we know something better (i.e. later) already?
1659 if (it->first < bestPos )
1662 // scope ends behind pos?
1663 if (pos < it->second.first) {
1664 // look for macro in external file
1665 d->macro_lock = true;
1666 MacroData const * data
1667 = it->second.second->getMacro(name, false);
1668 d->macro_lock = false;
1670 bestPos = it->first;
1676 // try previous file if there is one
1677 if (it == d->position_to_children.begin())
1682 // return the best macro we have found
1687 MacroData const * Buffer::getMacro(docstring const & name,
1688 DocIterator const & pos, bool global) const
1693 // query buffer macros
1694 MacroData const * data = getBufferMacro(name, pos);
1698 // If there is a master buffer, query that
1699 if (d->parent_buffer) {
1700 d->macro_lock = true;
1701 MacroData const * macro = d->parent_buffer->getMacro(
1702 name, *this, false);
1703 d->macro_lock = false;
1709 data = MacroTable::globalMacros().get(name);
1718 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1720 // set scope end behind the last paragraph
1721 DocIterator scope = par_iterator_begin();
1722 scope.pit() = scope.lastpit() + 1;
1724 return getMacro(name, scope, global);
1728 MacroData const * Buffer::getMacro(docstring const & name,
1729 Buffer const & child, bool global) const
1731 // look where the child buffer is included first
1732 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1733 if (it == d->children_positions.end())
1736 // check for macros at the inclusion position
1737 return getMacro(name, it->second, global);
1741 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1743 pit_type lastpit = it.lastpit();
1745 // look for macros in each paragraph
1746 while (it.pit() <= lastpit) {
1747 Paragraph & par = it.paragraph();
1749 // iterate over the insets of the current paragraph
1750 InsetList const & insets = par.insetList();
1751 InsetList::const_iterator iit = insets.begin();
1752 InsetList::const_iterator end = insets.end();
1753 for (; iit != end; ++iit) {
1754 it.pos() = iit->pos;
1756 // is it a nested text inset?
1757 if (iit->inset->asInsetText()) {
1758 // Inset needs its own scope?
1759 InsetText const * itext
1760 = iit->inset->asInsetText();
1761 bool newScope = itext->isMacroScope();
1763 // scope which ends just behind the inset
1764 DocIterator insetScope = it;
1767 // collect macros in inset
1768 it.push_back(CursorSlice(*iit->inset));
1769 updateMacros(it, newScope ? insetScope : scope);
1774 // is it an external file?
1775 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1776 // get buffer of external file
1777 InsetCommand const & inset
1778 = static_cast<InsetCommand const &>(*iit->inset);
1779 InsetCommandParams const & ip = inset.params();
1780 d->macro_lock = true;
1781 Buffer * child = loadIfNeeded(*this, ip);
1782 d->macro_lock = false;
1786 // register its position, but only when it is
1787 // included first in the buffer
1788 if (d->children_positions.find(child)
1789 == d->children_positions.end())
1790 d->children_positions[child] = it;
1792 // register child with its scope
1793 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1797 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1801 MathMacroTemplate & macroTemplate
1802 = static_cast<MathMacroTemplate &>(*iit->inset);
1803 MacroContext mc(*this, it);
1804 macroTemplate.updateToContext(mc);
1807 bool valid = macroTemplate.validMacro();
1808 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1809 // then the BufferView's cursor will be invalid in
1810 // some cases which leads to crashes.
1815 d->macros[macroTemplate.name()][it] =
1816 Impl::ScopeMacro(scope, MacroData(*this, it));
1826 void Buffer::updateMacros() const
1831 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1833 // start with empty table
1835 d->children_positions.clear();
1836 d->position_to_children.clear();
1838 // Iterate over buffer, starting with first paragraph
1839 // The scope must be bigger than any lookup DocIterator
1840 // later. For the global lookup, lastpit+1 is used, hence
1841 // we use lastpit+2 here.
1842 DocIterator it = par_iterator_begin();
1843 DocIterator outerScope = it;
1844 outerScope.pit() = outerScope.lastpit() + 2;
1845 updateMacros(it, outerScope);
1849 void Buffer::updateMacroInstances() const
1851 LYXERR(Debug::MACROS, "updateMacroInstances for "
1852 << d->filename.onlyFileName());
1853 DocIterator it = doc_iterator_begin(inset());
1854 DocIterator end = doc_iterator_end(inset());
1855 for (; it != end; it.forwardPos()) {
1856 // look for MathData cells in InsetMathNest insets
1857 Inset * inset = it.nextInset();
1861 InsetMath * minset = inset->asInsetMath();
1865 // update macro in all cells of the InsetMathNest
1866 DocIterator::idx_type n = minset->nargs();
1867 MacroContext mc = MacroContext(*this, it);
1868 for (DocIterator::idx_type i = 0; i < n; ++i) {
1869 MathData & data = minset->cell(i);
1870 data.updateMacros(0, mc);
1876 void Buffer::listMacroNames(MacroNameSet & macros) const
1881 d->macro_lock = true;
1883 // loop over macro names
1884 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1885 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1886 for (; nameIt != nameEnd; ++nameIt)
1887 macros.insert(nameIt->first);
1889 // loop over children
1890 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1891 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1892 for (; it != end; ++it)
1893 it->first->listMacroNames(macros);
1896 if (d->parent_buffer)
1897 d->parent_buffer->listMacroNames(macros);
1899 d->macro_lock = false;
1903 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
1905 if (!d->parent_buffer)
1909 d->parent_buffer->listMacroNames(names);
1912 MacroNameSet::iterator it = names.begin();
1913 MacroNameSet::iterator end = names.end();
1914 for (; it != end; ++it) {
1916 MacroData const * data =
1917 d->parent_buffer->getMacro(*it, *this, false);
1919 macros.insert(data);
1921 // we cannot access the original MathMacroTemplate anymore
1922 // here to calls validate method. So we do its work here manually.
1923 // FIXME: somehow make the template accessible here.
1924 if (data->optionals() > 0)
1925 features.require("xargs");
1931 Buffer::References & Buffer::references(docstring const & label)
1933 if (d->parent_buffer)
1934 return const_cast<Buffer *>(masterBuffer())->references(label);
1936 RefCache::iterator it = d->ref_cache_.find(label);
1937 if (it != d->ref_cache_.end())
1938 return it->second.second;
1940 static InsetLabel const * dummy_il = 0;
1941 static References const dummy_refs;
1942 it = d->ref_cache_.insert(
1943 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
1944 return it->second.second;
1948 Buffer::References const & Buffer::references(docstring const & label) const
1950 return const_cast<Buffer *>(this)->references(label);
1954 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
1956 masterBuffer()->d->ref_cache_[label].first = il;
1960 InsetLabel const * Buffer::insetLabel(docstring const & label) const
1962 return masterBuffer()->d->ref_cache_[label].first;
1966 void Buffer::clearReferenceCache() const
1968 if (!d->parent_buffer)
1969 d->ref_cache_.clear();
1973 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1976 //FIXME: This does not work for child documents yet.
1977 LASSERT(code == CITE_CODE, /**/);
1978 // Check if the label 'from' appears more than once
1979 vector<docstring> labels;
1982 keys.fillWithBibKeys(this);
1983 BiblioInfo::const_iterator bit = keys.begin();
1984 BiblioInfo::const_iterator bend = keys.end();
1986 for (; bit != bend; ++bit)
1988 labels.push_back(bit->first);
1991 if (count(labels.begin(), labels.end(), from) > 1)
1994 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1995 if (it->lyxCode() == code) {
1996 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1997 docstring const oldValue = inset.getParam(paramName);
1998 if (oldValue == from)
1999 inset.setParam(paramName, to);
2005 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2006 pit_type par_end, bool full_source)
2008 OutputParams runparams(¶ms().encoding());
2009 runparams.nice = true;
2010 runparams.flavor = OutputParams::LATEX;
2011 runparams.linelen = lyxrc.plaintext_linelen;
2012 // No side effect of file copying and image conversion
2013 runparams.dryrun = true;
2017 os << "% " << _("Preview source code") << "\n\n";
2018 d->texrow.newline();
2019 d->texrow.newline();
2021 writeLaTeXSource(os, filePath(), runparams, true, true);
2023 writeDocBookSource(os, absFileName(), runparams, false);
2025 runparams.par_begin = par_begin;
2026 runparams.par_end = par_end;
2027 if (par_begin + 1 == par_end) {
2029 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2033 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2034 convert<docstring>(par_begin),
2035 convert<docstring>(par_end - 1))
2038 d->texrow.newline();
2039 d->texrow.newline();
2040 // output paragraphs
2042 latexParagraphs(*this, text(), os, d->texrow, runparams);
2045 docbookParagraphs(paragraphs(), *this, os, runparams);
2050 ErrorList & Buffer::errorList(string const & type) const
2052 static ErrorList emptyErrorList;
2053 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2054 if (I == d->errorLists.end())
2055 return emptyErrorList;
2061 void Buffer::structureChanged() const
2064 gui_->structureChanged();
2068 void Buffer::errors(string const & err) const
2075 void Buffer::message(docstring const & msg) const
2082 void Buffer::setBusy(bool on) const
2089 void Buffer::setReadOnly(bool on) const
2092 d->wa_->setReadOnly(on);
2096 void Buffer::updateTitles() const
2099 d->wa_->updateTitles();
2103 void Buffer::resetAutosaveTimers() const
2106 gui_->resetAutosaveTimers();
2110 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2119 class AutoSaveBuffer : public ForkedProcess {
2122 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2123 : buffer_(buffer), fname_(fname) {}
2125 virtual boost::shared_ptr<ForkedProcess> clone() const
2127 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2132 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2133 from_utf8(fname_.absFilename())));
2134 return run(DontWait);
2138 virtual int generateChild();
2140 Buffer const & buffer_;
2145 int AutoSaveBuffer::generateChild()
2147 // tmp_ret will be located (usually) in /tmp
2148 // will that be a problem?
2149 // Note that this calls ForkedCalls::fork(), so it's
2150 // ok cross-platform.
2151 pid_t const pid = fork();
2152 // If you want to debug the autosave
2153 // you should set pid to -1, and comment out the fork.
2154 if (pid != 0 && pid != -1)
2157 // pid = -1 signifies that lyx was unable
2158 // to fork. But we will do the save
2160 bool failed = false;
2161 FileName const tmp_ret = FileName::tempName("lyxauto");
2162 if (!tmp_ret.empty()) {
2163 buffer_.writeFile(tmp_ret);
2164 // assume successful write of tmp_ret
2165 if (!tmp_ret.moveTo(fname_))
2171 // failed to write/rename tmp_ret so try writing direct
2172 if (!buffer_.writeFile(fname_)) {
2173 // It is dangerous to do this in the child,
2174 // but safe in the parent, so...
2175 if (pid == -1) // emit message signal.
2176 buffer_.message(_("Autosave failed!"));
2180 if (pid == 0) // we are the child so...
2189 // Perfect target for a thread...
2190 void Buffer::autoSave() const
2192 if (isBakClean() || isReadonly()) {
2193 // We don't save now, but we'll try again later
2194 resetAutosaveTimers();
2198 // emit message signal.
2199 message(_("Autosaving current document..."));
2201 // create autosave filename
2202 string fname = filePath();
2204 fname += d->filename.onlyFileName();
2207 AutoSaveBuffer autosave(*this, FileName(fname));
2211 resetAutosaveTimers();
2215 string Buffer::bufferFormat() const
2225 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2226 string & result_file) const
2228 string backend_format;
2229 OutputParams runparams(¶ms().encoding());
2230 runparams.flavor = OutputParams::LATEX;
2231 runparams.linelen = lyxrc.plaintext_linelen;
2232 vector<string> backs = backends();
2233 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2234 // Get shortest path to format
2235 Graph::EdgePath path;
2236 for (vector<string>::const_iterator it = backs.begin();
2237 it != backs.end(); ++it) {
2238 Graph::EdgePath p = theConverters().getPath(*it, format);
2239 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2240 backend_format = *it;
2245 runparams.flavor = theConverters().getFlavor(path);
2247 Alert::error(_("Couldn't export file"),
2248 bformat(_("No information for exporting the format %1$s."),
2249 formats.prettyName(format)));
2253 backend_format = format;
2254 // FIXME: Don't hardcode format names here, but use a flag
2255 if (backend_format == "pdflatex")
2256 runparams.flavor = OutputParams::PDFLATEX;
2259 string filename = latexName(false);
2260 filename = addName(temppath(), filename);
2261 filename = changeExtension(filename,
2262 formats.extension(backend_format));
2265 updateMacroInstances();
2267 // Plain text backend
2268 if (backend_format == "text")
2269 writePlaintextFile(*this, FileName(filename), runparams);
2271 else if (backend_format == "lyx")
2272 writeFile(FileName(filename));
2274 else if (isDocBook()) {
2275 runparams.nice = !put_in_tempdir;
2276 makeDocBookFile(FileName(filename), runparams);
2279 else if (backend_format == format) {
2280 runparams.nice = true;
2281 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2283 } else if (!lyxrc.tex_allows_spaces
2284 && contains(filePath(), ' ')) {
2285 Alert::error(_("File name error"),
2286 _("The directory path to the document cannot contain spaces."));
2289 runparams.nice = false;
2290 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2294 string const error_type = (format == "program")
2295 ? "Build" : bufferFormat();
2296 string const ext = formats.extension(format);
2297 FileName const tmp_result_file(changeExtension(filename, ext));
2298 bool const success = theConverters().convert(this, FileName(filename),
2299 tmp_result_file, FileName(absFileName()), backend_format, format,
2300 errorList(error_type));
2301 // Emit the signal to show the error list.
2302 if (format != backend_format)
2307 if (put_in_tempdir) {
2308 result_file = tmp_result_file.absFilename();
2312 result_file = changeExtension(absFileName(), ext);
2313 // We need to copy referenced files (e. g. included graphics
2314 // if format == "dvi") to the result dir.
2315 vector<ExportedFile> const files =
2316 runparams.exportdata->externalFiles(format);
2317 string const dest = onlyPath(result_file);
2318 CopyStatus status = SUCCESS;
2319 for (vector<ExportedFile>::const_iterator it = files.begin();
2320 it != files.end() && status != CANCEL; ++it) {
2321 string const fmt = formats.getFormatFromFile(it->sourceName);
2322 status = copyFile(fmt, it->sourceName,
2323 makeAbsPath(it->exportName, dest),
2324 it->exportName, status == FORCE);
2326 if (status == CANCEL) {
2327 message(_("Document export cancelled."));
2328 } else if (tmp_result_file.exists()) {
2329 // Finally copy the main file
2330 status = copyFile(format, tmp_result_file,
2331 FileName(result_file), result_file,
2333 message(bformat(_("Document exported as %1$s "
2335 formats.prettyName(format),
2336 makeDisplayPath(result_file)));
2338 // This must be a dummy converter like fax (bug 1888)
2339 message(bformat(_("Document exported as %1$s"),
2340 formats.prettyName(format)));
2347 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2350 return doExport(format, put_in_tempdir, result_file);
2354 bool Buffer::preview(string const & format) const
2357 if (!doExport(format, true, result_file))
2359 return formats.view(*this, FileName(result_file), format);
2363 bool Buffer::isExportable(string const & format) const
2365 vector<string> backs = backends();
2366 for (vector<string>::const_iterator it = backs.begin();
2367 it != backs.end(); ++it)
2368 if (theConverters().isReachable(*it, format))
2374 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2376 vector<string> backs = backends();
2377 vector<Format const *> result =
2378 theConverters().getReachable(backs[0], only_viewable, true);
2379 for (vector<string>::const_iterator it = backs.begin() + 1;
2380 it != backs.end(); ++it) {
2381 vector<Format const *> r =
2382 theConverters().getReachable(*it, only_viewable, false);
2383 result.insert(result.end(), r.begin(), r.end());
2389 vector<string> Buffer::backends() const
2392 if (params().baseClass()->isTeXClassAvailable()) {
2393 v.push_back(bufferFormat());
2394 // FIXME: Don't hardcode format names here, but use a flag
2395 if (v.back() == "latex")
2396 v.push_back("pdflatex");
2398 v.push_back("text");
2404 bool Buffer::readFileHelper(FileName const & s)
2406 // File information about normal file
2408 docstring const file = makeDisplayPath(s.absFilename(), 50);
2409 docstring text = bformat(_("The specified document\n%1$s"
2410 "\ncould not be read."), file);
2411 Alert::error(_("Could not read document"), text);
2415 // Check if emergency save file exists and is newer.
2416 FileName const e(s.absFilename() + ".emergency");
2418 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2419 docstring const file = makeDisplayPath(s.absFilename(), 20);
2420 docstring const text =
2421 bformat(_("An emergency save of the document "
2423 "Recover emergency save?"), file);
2424 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2425 _("&Recover"), _("&Load Original"),
2429 // the file is not saved if we load the emergency file.
2439 // Now check if autosave file is newer.
2440 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2442 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2443 docstring const file = makeDisplayPath(s.absFilename(), 20);
2444 docstring const text =
2445 bformat(_("The backup of the document "
2446 "%1$s is newer.\n\nLoad the "
2447 "backup instead?"), file);
2448 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2449 _("&Load backup"), _("Load &original"),
2453 // the file is not saved if we load the autosave file.
2457 // Here we delete the autosave
2468 bool Buffer::loadLyXFile(FileName const & s)
2470 if (s.isReadableFile()) {
2471 if (readFileHelper(s)) {
2472 lyxvc().file_found_hook(s);
2473 if (!s.isWritable())
2478 docstring const file = makeDisplayPath(s.absFilename(), 20);
2479 // Here we probably should run
2480 if (LyXVC::file_not_found_hook(s)) {
2481 docstring const text =
2482 bformat(_("Do you want to retrieve the document"
2483 " %1$s from version control?"), file);
2484 int const ret = Alert::prompt(_("Retrieve from version control?"),
2485 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2488 // How can we know _how_ to do the checkout?
2489 // With the current VC support it has to be,
2490 // a RCS file since CVS do not have special ,v files.
2492 return loadLyXFile(s);
2500 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2502 TeXErrors::Errors::const_iterator cit = terr.begin();
2503 TeXErrors::Errors::const_iterator end = terr.end();
2505 for (; cit != end; ++cit) {
2508 int errorRow = cit->error_in_line;
2509 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2515 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2516 } while (found && id_start == id_end && pos_start == pos_end);
2518 errorList.push_back(ErrorItem(cit->error_desc,
2519 cit->error_text, id_start, pos_start, pos_end));