3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
48 #include "output_docbook.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetText.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include <boost/bind.hpp>
107 #include <boost/shared_ptr.hpp>
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 373; // jspitzm: merge g-brief class
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
150 Impl(Buffer & parent, FileName const & file, bool readonly);
164 mutable TexRow texrow;
166 /// need to regenerate .tex?
170 mutable bool lyx_clean;
172 /// is autosave needed?
173 mutable bool bak_clean;
175 /// is this a unnamed file (New...)?
181 /// name of the file the buffer is associated with.
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
191 mutable TocBackend toc_backend;
194 typedef pair<DocIterator, MacroData> ScopeMacro;
195 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
196 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
197 /// map from the macro name to the position map,
198 /// which maps the macro definition position to the scope and the MacroData.
199 NamePositionScopeMacroMap macros;
202 /// positions of child buffers in the buffer
203 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
204 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
205 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
206 /// position of children buffers in this buffer
207 BufferPositionMap children_positions;
208 /// map from children inclusion positions to their scope and their buffer
209 PositionScopeBufferMap position_to_children;
211 /// Container for all sort of Buffer dependant errors.
212 map<string, ErrorList> errorLists;
214 /// timestamp and checksum used to test if the file has been externally
215 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
217 unsigned long checksum_;
220 frontend::WorkAreaManager * wa_;
225 /// A cache for the bibfiles (including bibfiles of loaded child
226 /// documents), needed for appropriate update of natbib labels.
227 mutable support::FileNameList bibfilesCache_;
229 // FIXME The caching mechanism could be improved. At present, we have a
230 // cache for each Buffer, that caches all the bibliography info for that
231 // Buffer. A more efficient solution would be to have a global cache per
232 // file, and then to construct the Buffer's bibinfo from that.
233 /// A cache for bibliography info
234 mutable BiblioInfo bibinfo_;
235 /// whether the bibinfo cache is valid
236 bool bibinfoCacheValid_;
237 /// Cache of timestamps of .bib files
238 map<FileName, time_t> bibfileStatus_;
240 mutable RefCache ref_cache_;
242 /// our Text that should be wrapped in an InsetText
245 /// This is here to force the test to be done whenever parent_buffer
247 Buffer const * parent() const {
248 // if parent_buffer is not loaded, then it has been unloaded,
249 // which means that parent_buffer is an invalid pointer. So we
250 // set it to null in that case.
251 if (!theBufferList().isLoaded(parent_buffer))
253 return parent_buffer;
256 void setParent(Buffer const * pb) {
257 if (parent_buffer && pb && parent_buffer != pb)
258 LYXERR0("Warning: a buffer should not have two parents!");
262 /// So we can force access via the accessors.
263 mutable Buffer const * parent_buffer;
267 /// Creates the per buffer temporary directory
268 static FileName createBufferTmpDir()
271 // We are in our own directory. Why bother to mangle name?
272 // In fact I wrote this code to circumvent a problematic behaviour
273 // (bug?) of EMX mkstemp().
274 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
275 convert<string>(count++));
277 if (!tmpfl.createDirectory(0777)) {
278 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
279 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
280 from_utf8(tmpfl.absFilename())));
286 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
287 : lyx_clean(true), bak_clean(true), unnamed(false),
288 read_only(readonly_), filename(file), file_fully_loaded(false),
289 toc_backend(&parent), macro_lock(false), timestamp_(0),
290 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
293 temppath = createBufferTmpDir();
294 lyxvc.setBuffer(&parent);
296 wa_ = new frontend::WorkAreaManager;
300 Buffer::Buffer(string const & file, bool readonly)
301 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
303 LYXERR(Debug::INFO, "Buffer::Buffer()");
305 d->inset = new InsetText(this);
306 d->inset->setAutoBreakRows(true);
307 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
313 LYXERR(Debug::INFO, "Buffer::~Buffer()");
314 // here the buffer should take care that it is
315 // saved properly, before it goes into the void.
317 // GuiView already destroyed
321 // No need to do additional cleanups for internal buffer.
326 // loop over children
327 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
328 Impl::BufferPositionMap::iterator end = d->children_positions.end();
329 for (; it != end; ++it) {
330 Buffer * child = const_cast<Buffer *>(it->first);
331 // The child buffer might have been closed already.
332 if (theBufferList().isLoaded(child))
333 theBufferList().releaseChild(this, child);
337 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
338 msg += emergencyWrite();
339 frontend::Alert::warning(_("Attempting to close changed document!"), msg);
342 // clear references to children in macro tables
343 d->children_positions.clear();
344 d->position_to_children.clear();
346 if (!d->temppath.destroyDirectory()) {
347 Alert::warning(_("Could not remove temporary directory"),
348 bformat(_("Could not remove the temporary directory %1$s"),
349 from_utf8(d->temppath.absFilename())));
352 // Remove any previewed LaTeX snippets associated with this buffer.
353 thePreviews().removeLoader(*this);
359 Buffer * Buffer::clone() const
361 Buffer * clone = new Buffer(fileName().absFilename(), false);
362 clone->d->file_fully_loaded = true;
363 clone->d->params = d->params;
364 clone->d->inset = static_cast<InsetText *>(d->inset->clone());
365 clone->d->inset->setBuffer(*clone);
370 void Buffer::changed() const
377 frontend::WorkAreaManager & Buffer::workAreaManager() const
379 LASSERT(d->wa_, /**/);
384 Text & Buffer::text() const
386 return d->inset->text();
390 Inset & Buffer::inset() const
396 BufferParams & Buffer::params()
402 BufferParams const & Buffer::params() const
408 ParagraphList & Buffer::paragraphs()
410 return text().paragraphs();
414 ParagraphList const & Buffer::paragraphs() const
416 return text().paragraphs();
420 LyXVC & Buffer::lyxvc()
426 LyXVC const & Buffer::lyxvc() const
432 string const Buffer::temppath() const
434 return d->temppath.absFilename();
438 TexRow & Buffer::texrow()
444 TexRow const & Buffer::texrow() const
450 TocBackend & Buffer::tocBackend() const
452 return d->toc_backend;
456 Undo & Buffer::undo()
462 string Buffer::latexName(bool const no_path) const
464 FileName latex_name =
465 makeLatexName(exportFileName());
466 return no_path ? latex_name.onlyFileName()
467 : latex_name.absFilename();
471 FileName Buffer::exportFileName() const
473 docstring const branch_suffix =
474 params().branchlist().getFilenameSuffix();
475 if (branch_suffix.empty())
478 string const name = fileName().onlyFileNameWithoutExt()
479 + to_utf8(branch_suffix);
480 FileName res(fileName().onlyPath().absFilename() + "/" + name);
481 res.changeExtension(fileName().extension());
487 string Buffer::logName(LogType * type) const
489 string const filename = latexName(false);
491 if (filename.empty()) {
497 string const path = temppath();
499 FileName const fname(addName(temppath(),
500 onlyFilename(changeExtension(filename,
503 // FIXME: how do we know this is the name of the build log?
504 FileName const bname(
505 addName(path, onlyFilename(
506 changeExtension(filename,
507 formats.extension(bufferFormat()) + ".out"))));
509 // Also consider the master buffer log file
510 FileName masterfname = fname;
512 if (masterBuffer() != this) {
513 string const mlogfile = masterBuffer()->logName(&mtype);
514 masterfname = FileName(mlogfile);
517 // If no Latex log or Build log is newer, show Build log
518 if (bname.exists() &&
519 ((!fname.exists() && !masterfname.exists())
520 || (fname.lastModified() < bname.lastModified()
521 && masterfname.lastModified() < bname.lastModified()))) {
522 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
525 return bname.absFilename();
526 // If we have a newer master file log or only a master log, show this
527 } else if (fname != masterfname
528 && (!fname.exists() && (masterfname.exists()
529 || fname.lastModified() < masterfname.lastModified()))) {
530 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
533 return masterfname.absFilename();
535 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
538 return fname.absFilename();
542 void Buffer::setReadonly(bool const flag)
544 if (d->read_only != flag) {
551 void Buffer::setFileName(string const & newfile)
553 d->filename = makeAbsPath(newfile);
554 setReadonly(d->filename.isReadOnly());
559 int Buffer::readHeader(Lexer & lex)
561 int unknown_tokens = 0;
563 int begin_header_line = -1;
565 // Initialize parameters that may be/go lacking in header:
566 params().branchlist().clear();
567 params().preamble.erase();
568 params().options.erase();
569 params().master.erase();
570 params().float_placement.erase();
571 params().paperwidth.erase();
572 params().paperheight.erase();
573 params().leftmargin.erase();
574 params().rightmargin.erase();
575 params().topmargin.erase();
576 params().bottommargin.erase();
577 params().headheight.erase();
578 params().headsep.erase();
579 params().footskip.erase();
580 params().columnsep.erase();
581 params().fontsCJK.erase();
582 params().listings_params.clear();
583 params().clearLayoutModules();
584 params().clearRemovedModules();
585 params().pdfoptions().clear();
586 params().indiceslist().clear();
587 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
589 for (int i = 0; i < 4; ++i) {
590 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
591 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
594 ErrorList & errorList = d->errorLists["Parse"];
603 if (token == "\\end_header")
607 if (token == "\\begin_header") {
608 begin_header_line = line;
612 LYXERR(Debug::PARSER, "Handling document header token: `"
615 string unknown = params().readToken(lex, token, d->filename.onlyPath());
616 if (!unknown.empty()) {
617 if (unknown[0] != '\\' && token == "\\textclass") {
618 Alert::warning(_("Unknown document class"),
619 bformat(_("Using the default document class, because the "
620 "class %1$s is unknown."), from_utf8(unknown)));
623 docstring const s = bformat(_("Unknown token: "
627 errorList.push_back(ErrorItem(_("Document header error"),
632 if (begin_header_line) {
633 docstring const s = _("\\begin_header is missing");
634 errorList.push_back(ErrorItem(_("Document header error"),
638 params().makeDocumentClass();
640 return unknown_tokens;
645 // changed to be public and have one parameter
646 // Returns true if "\end_document" is not read (Asger)
647 bool Buffer::readDocument(Lexer & lex)
649 ErrorList & errorList = d->errorLists["Parse"];
652 if (!lex.checkFor("\\begin_document")) {
653 docstring const s = _("\\begin_document is missing");
654 errorList.push_back(ErrorItem(_("Document header error"),
658 // we are reading in a brand new document
659 LASSERT(paragraphs().empty(), /**/);
663 if (params().outputChanges) {
664 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
665 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
666 LaTeXFeatures::isAvailable("xcolor");
668 if (!dvipost && !xcolorulem) {
669 Alert::warning(_("Changes not shown in LaTeX output"),
670 _("Changes will not be highlighted in LaTeX output, "
671 "because neither dvipost nor xcolor/ulem are installed.\n"
672 "Please install these packages or redefine "
673 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
674 } else if (!xcolorulem) {
675 Alert::warning(_("Changes not shown in LaTeX output"),
676 _("Changes will not be highlighted in LaTeX output "
677 "when using pdflatex, because xcolor and ulem are not installed.\n"
678 "Please install both packages or redefine "
679 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
683 if (!params().master.empty()) {
684 FileName const master_file = makeAbsPath(params().master,
685 onlyPath(absFileName()));
686 if (isLyXFilename(master_file.absFilename())) {
688 checkAndLoadLyXFile(master_file, true);
690 // necessary e.g. after a reload
691 // to re-register the child (bug 5873)
692 // FIXME: clean up updateMacros (here, only
693 // child registering is needed).
694 master->updateMacros();
695 // set master as master buffer, but only
696 // if we are a real child
697 if (master->isChild(this))
699 // if the master is not fully loaded
700 // it is probably just loading this
701 // child. No warning needed then.
702 else if (master->isFullyLoaded())
703 LYXERR0("The master '"
705 << "' assigned to this document ("
707 << ") does not include "
708 "this document. Ignoring the master assignment.");
713 // assure we have a default index
714 params().indiceslist().addDefault(B_("Index"));
717 bool const res = text().read(lex, errorList, d->inset);
721 updateMacroInstances();
726 bool Buffer::readString(string const & s)
728 params().compressed = false;
730 // remove dummy empty par
731 paragraphs().clear();
735 FileName const name = FileName::tempName("Buffer_readString");
736 switch (readFile(lex, name, true)) {
740 // We need to call lyx2lyx, so write the input to a file
741 ofstream os(name.toFilesystemEncoding().c_str());
744 return readFile(name);
754 bool Buffer::readFile(FileName const & filename)
756 FileName fname(filename);
758 params().compressed = fname.isZippedFile();
760 // remove dummy empty par
761 paragraphs().clear();
764 if (readFile(lex, fname) != success)
771 bool Buffer::isFullyLoaded() const
773 return d->file_fully_loaded;
777 void Buffer::setFullyLoaded(bool value)
779 d->file_fully_loaded = value;
783 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
786 LASSERT(!filename.empty(), /**/);
788 // the first (non-comment) token _must_ be...
789 if (!lex.checkFor("\\lyxformat")) {
790 Alert::error(_("Document format failure"),
791 bformat(_("%1$s is not a readable LyX document."),
792 from_utf8(filename.absFilename())));
798 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
799 // if present remove ".," from string.
800 size_t dot = tmp_format.find_first_of(".,");
801 //lyxerr << " dot found at " << dot << endl;
802 if (dot != string::npos)
803 tmp_format.erase(dot, 1);
804 int const file_format = convert<int>(tmp_format);
805 //lyxerr << "format: " << file_format << endl;
807 // save timestamp and checksum of the original disk file, making sure
808 // to not overwrite them with those of the file created in the tempdir
809 // when it has to be converted to the current format.
811 // Save the timestamp and checksum of disk file. If filename is an
812 // emergency file, save the timestamp and checksum of the original lyx file
813 // because isExternallyModified will check for this file. (BUG4193)
814 string diskfile = filename.absFilename();
815 if (suffixIs(diskfile, ".emergency"))
816 diskfile = diskfile.substr(0, diskfile.size() - 10);
817 saveCheckSum(FileName(diskfile));
820 if (file_format != LYX_FORMAT) {
823 // lyx2lyx would fail
826 FileName const tmpfile = FileName::tempName("Buffer_readFile");
827 if (tmpfile.empty()) {
828 Alert::error(_("Conversion failed"),
829 bformat(_("%1$s is from a different"
830 " version of LyX, but a temporary"
831 " file for converting it could"
833 from_utf8(filename.absFilename())));
836 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
837 if (lyx2lyx.empty()) {
838 Alert::error(_("Conversion script not found"),
839 bformat(_("%1$s is from a different"
840 " version of LyX, but the"
841 " conversion script lyx2lyx"
842 " could not be found."),
843 from_utf8(filename.absFilename())));
846 ostringstream command;
847 command << os::python()
848 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
849 << " -t " << convert<string>(LYX_FORMAT)
850 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
851 << ' ' << quoteName(filename.toFilesystemEncoding());
852 string const command_str = command.str();
854 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
856 cmd_ret const ret = runCommand(command_str);
857 if (ret.first != 0) {
858 Alert::error(_("Conversion script failed"),
859 bformat(_("%1$s is from a different version"
860 " of LyX, but the lyx2lyx script"
861 " failed to convert it."),
862 from_utf8(filename.absFilename())));
865 bool const ret = readFile(tmpfile);
866 // Do stuff with tmpfile name and buffer name here.
867 return ret ? success : failure;
872 if (readDocument(lex)) {
873 Alert::error(_("Document format failure"),
874 bformat(_("%1$s ended unexpectedly, which means"
875 " that it is probably corrupted."),
876 from_utf8(filename.absFilename())));
879 d->file_fully_loaded = true;
884 // Should probably be moved to somewhere else: BufferView? LyXView?
885 bool Buffer::save() const
887 // We don't need autosaves in the immediate future. (Asger)
888 resetAutosaveTimers();
890 string const encodedFilename = d->filename.toFilesystemEncoding();
893 bool madeBackup = false;
895 // make a backup if the file already exists
896 if (lyxrc.make_backup && fileName().exists()) {
897 backupName = FileName(absFileName() + '~');
898 if (!lyxrc.backupdir_path.empty()) {
899 string const mangledName =
900 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
901 backupName = FileName(addName(lyxrc.backupdir_path,
904 if (fileName().copyTo(backupName)) {
907 Alert::error(_("Backup failure"),
908 bformat(_("Cannot create backup file %1$s.\n"
909 "Please check whether the directory exists and is writeable."),
910 from_utf8(backupName.absFilename())));
911 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
915 // ask if the disk file has been externally modified (use checksum method)
916 if (fileName().exists() && isExternallyModified(checksum_method)) {
917 docstring const file = makeDisplayPath(absFileName(), 20);
918 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
919 "you want to overwrite this file?"), file);
920 int const ret = Alert::prompt(_("Overwrite modified file?"),
921 text, 1, 1, _("&Overwrite"), _("&Cancel"));
926 if (writeFile(d->filename)) {
930 // Saving failed, so backup is not backup
932 backupName.moveTo(d->filename);
938 bool Buffer::writeFile(FileName const & fname) const
940 if (d->read_only && fname == d->filename)
945 docstring const str = bformat(_("Saving document %1$s..."),
946 makeDisplayPath(fname.absFilename()));
949 if (params().compressed) {
950 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
951 retval = ofs && write(ofs);
953 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
954 retval = ofs && write(ofs);
958 message(str + _(" could not write file!"));
962 removeAutosaveFile();
964 saveCheckSum(d->filename);
965 message(str + _(" done."));
971 docstring Buffer::emergencyWrite()
973 // No need to save if the buffer has not changed.
977 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
979 docstring user_message = bformat(
980 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
982 // We try to save three places:
983 // 1) Same place as document. Unless it is an unnamed doc.
985 string s = absFileName();
988 if (writeFile(FileName(s))) {
990 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
993 user_message += _(" Save failed! Trying again...\n");
997 // 2) In HOME directory.
998 string s = addName(package().home_dir().absFilename(), absFileName());
1000 lyxerr << ' ' << s << endl;
1001 if (writeFile(FileName(s))) {
1003 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1004 return user_message;
1007 user_message += _(" Save failed! Trying yet again...\n");
1009 // 3) In "/tmp" directory.
1010 // MakeAbsPath to prepend the current
1011 // drive letter on OS/2
1012 s = addName(package().temp_dir().absFilename(), absFileName());
1014 lyxerr << ' ' << s << endl;
1015 if (writeFile(FileName(s))) {
1017 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1018 return user_message;
1021 user_message += _(" Save failed! Bummer. Document is lost.");
1024 return user_message;
1028 bool Buffer::write(ostream & ofs) const
1031 // Use the standard "C" locale for file output.
1032 ofs.imbue(locale::classic());
1035 // The top of the file should not be written by params().
1037 // write out a comment in the top of the file
1038 ofs << "#LyX " << lyx_version
1039 << " created this file. For more info see http://www.lyx.org/\n"
1040 << "\\lyxformat " << LYX_FORMAT << "\n"
1041 << "\\begin_document\n";
1043 /// For each author, set 'used' to true if there is a change
1044 /// by this author in the document; otherwise set it to 'false'.
1045 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1046 AuthorList::Authors::const_iterator a_end = params().authors().end();
1047 for (; a_it != a_end; ++a_it)
1048 a_it->setUsed(false);
1050 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1051 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1052 for ( ; it != end; ++it)
1053 it->checkAuthors(params().authors());
1055 // now write out the buffer parameters.
1056 ofs << "\\begin_header\n";
1057 params().writeFile(ofs);
1058 ofs << "\\end_header\n";
1061 ofs << "\n\\begin_body\n";
1063 ofs << "\n\\end_body\n";
1065 // Write marker that shows file is complete
1066 ofs << "\\end_document" << endl;
1068 // Shouldn't really be needed....
1071 // how to check if close went ok?
1072 // Following is an attempt... (BE 20001011)
1074 // good() returns false if any error occured, including some
1075 // formatting error.
1076 // bad() returns true if something bad happened in the buffer,
1077 // which should include file system full errors.
1082 lyxerr << "File was not closed properly." << endl;
1089 bool Buffer::makeLaTeXFile(FileName const & fname,
1090 string const & original_path,
1091 OutputParams const & runparams_in,
1092 bool output_preamble, bool output_body) const
1094 OutputParams runparams = runparams_in;
1095 if (params().useXetex)
1096 runparams.flavor = OutputParams::XETEX;
1098 string const encoding = runparams.encoding->iconvName();
1099 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1102 try { ofs.reset(encoding); }
1103 catch (iconv_codecvt_facet_exception & e) {
1104 lyxerr << "Caught iconv exception: " << e.what() << endl;
1105 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1106 "verify that the support software for your encoding (%1$s) is "
1107 "properly installed"), from_ascii(encoding)));
1110 if (!openFileWrite(ofs, fname))
1113 //TexStream ts(ofs.rdbuf(), &texrow());
1114 ErrorList & errorList = d->errorLists["Export"];
1116 bool failed_export = false;
1119 writeLaTeXSource(ofs, original_path,
1120 runparams, output_preamble, output_body);
1122 catch (EncodingException & e) {
1123 odocstringstream ods;
1124 ods.put(e.failed_char);
1126 oss << "0x" << hex << e.failed_char << dec;
1127 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1128 " (code point %2$s)"),
1129 ods.str(), from_utf8(oss.str()));
1130 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1131 "representable in the chosen encoding.\n"
1132 "Changing the document encoding to utf8 could help."),
1133 e.par_id, e.pos, e.pos + 1));
1134 failed_export = true;
1136 catch (iconv_codecvt_facet_exception & e) {
1137 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1138 _(e.what()), -1, 0, 0));
1139 failed_export = true;
1141 catch (exception const & e) {
1142 errorList.push_back(ErrorItem(_("conversion failed"),
1143 _(e.what()), -1, 0, 0));
1144 failed_export = true;
1147 lyxerr << "Caught some really weird exception..." << endl;
1153 failed_export = true;
1154 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1158 return !failed_export;
1162 void Buffer::writeLaTeXSource(odocstream & os,
1163 string const & original_path,
1164 OutputParams const & runparams_in,
1165 bool const output_preamble, bool const output_body) const
1167 // The child documents, if any, shall be already loaded at this point.
1169 OutputParams runparams = runparams_in;
1171 // Classify the unicode characters appearing in math insets
1172 Encodings::initUnicodeMath(*this);
1174 // validate the buffer.
1175 LYXERR(Debug::LATEX, " Validating buffer...");
1176 LaTeXFeatures features(*this, params(), runparams);
1178 LYXERR(Debug::LATEX, " Buffer validation done.");
1180 // The starting paragraph of the coming rows is the
1181 // first paragraph of the document. (Asger)
1182 if (output_preamble && runparams.nice) {
1183 os << "%% LyX " << lyx_version << " created this file. "
1184 "For more info, see http://www.lyx.org/.\n"
1185 "%% Do not edit unless you really know what "
1187 d->texrow.newline();
1188 d->texrow.newline();
1190 LYXERR(Debug::INFO, "lyx document header finished");
1192 // Don't move this behind the parent_buffer=0 code below,
1193 // because then the macros will not get the right "redefinition"
1194 // flag as they don't see the parent macros which are output before.
1197 // fold macros if possible, still with parent buffer as the
1198 // macros will be put in the prefix anyway.
1199 updateMacroInstances();
1201 // There are a few differences between nice LaTeX and usual files:
1202 // usual is \batchmode and has a
1203 // special input@path to allow the including of figures
1204 // with either \input or \includegraphics (what figinsets do).
1205 // input@path is set when the actual parameter
1206 // original_path is set. This is done for usual tex-file, but not
1207 // for nice-latex-file. (Matthias 250696)
1208 // Note that input@path is only needed for something the user does
1209 // in the preamble, included .tex files or ERT, files included by
1210 // LyX work without it.
1211 if (output_preamble) {
1212 if (!runparams.nice) {
1213 // code for usual, NOT nice-latex-file
1214 os << "\\batchmode\n"; // changed
1215 // from \nonstopmode
1216 d->texrow.newline();
1218 if (!original_path.empty()) {
1220 // We don't know the encoding of inputpath
1221 docstring const inputpath = from_utf8(latex_path(original_path));
1222 os << "\\makeatletter\n"
1223 << "\\def\\input@path{{"
1224 << inputpath << "/}}\n"
1225 << "\\makeatother\n";
1226 d->texrow.newline();
1227 d->texrow.newline();
1228 d->texrow.newline();
1231 // get parent macros (if this buffer has a parent) which will be
1232 // written at the document begin further down.
1233 MacroSet parentMacros;
1234 listParentMacros(parentMacros, features);
1236 // Write the preamble
1237 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1239 runparams.use_japanese = features.isRequired("japanese");
1245 os << "\\begin{document}\n";
1246 d->texrow.newline();
1248 // output the parent macros
1249 MacroSet::iterator it = parentMacros.begin();
1250 MacroSet::iterator end = parentMacros.end();
1251 for (; it != end; ++it)
1252 (*it)->write(os, true);
1253 } // output_preamble
1255 d->texrow.start(paragraphs().begin()->id(), 0);
1257 LYXERR(Debug::INFO, "preamble finished, now the body.");
1259 // if we are doing a real file with body, even if this is the
1260 // child of some other buffer, let's cut the link here.
1261 // This happens for example if only a child document is printed.
1262 Buffer const * save_parent = 0;
1263 if (output_preamble) {
1264 save_parent = d->parent();
1269 latexParagraphs(*this, text(), os, d->texrow, runparams);
1271 // Restore the parenthood if needed
1272 if (output_preamble)
1273 d->setParent(save_parent);
1275 // add this just in case after all the paragraphs
1277 d->texrow.newline();
1279 if (output_preamble) {
1280 os << "\\end{document}\n";
1281 d->texrow.newline();
1282 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1284 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1286 runparams_in.encoding = runparams.encoding;
1288 // Just to be sure. (Asger)
1289 d->texrow.newline();
1291 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1292 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1296 bool Buffer::isLatex() const
1298 return params().documentClass().outputType() == LATEX;
1302 bool Buffer::isLiterate() const
1304 return params().documentClass().outputType() == LITERATE;
1308 bool Buffer::isDocBook() const
1310 return params().documentClass().outputType() == DOCBOOK;
1314 void Buffer::makeDocBookFile(FileName const & fname,
1315 OutputParams const & runparams,
1316 bool const body_only) const
1318 LYXERR(Debug::LATEX, "makeDocBookFile...");
1321 if (!openFileWrite(ofs, fname))
1324 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1328 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1332 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1333 OutputParams const & runparams,
1334 bool const only_body) const
1336 LaTeXFeatures features(*this, params(), runparams);
1341 DocumentClass const & tclass = params().documentClass();
1342 string const top_element = tclass.latexname();
1345 if (runparams.flavor == OutputParams::XML)
1346 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1349 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1352 if (! tclass.class_header().empty())
1353 os << from_ascii(tclass.class_header());
1354 else if (runparams.flavor == OutputParams::XML)
1355 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1356 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1358 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1360 docstring preamble = from_utf8(params().preamble);
1361 if (runparams.flavor != OutputParams::XML ) {
1362 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1363 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1364 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1365 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1368 string const name = runparams.nice
1369 ? changeExtension(absFileName(), ".sgml") : fname;
1370 preamble += features.getIncludedFiles(name);
1371 preamble += features.getLyXSGMLEntities();
1373 if (!preamble.empty()) {
1374 os << "\n [ " << preamble << " ]";
1379 string top = top_element;
1381 if (runparams.flavor == OutputParams::XML)
1382 top += params().language->code();
1384 top += params().language->code().substr(0, 2);
1387 if (!params().options.empty()) {
1389 top += params().options;
1392 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1393 << " file was created by LyX " << lyx_version
1394 << "\n See http://www.lyx.org/ for more information -->\n";
1396 params().documentClass().counters().reset();
1400 sgml::openTag(os, top);
1402 docbookParagraphs(text(), *this, os, runparams);
1403 sgml::closeTag(os, top_element);
1407 void Buffer::makeLyXHTMLFile(FileName const & fname,
1408 OutputParams const & runparams,
1409 bool const body_only) const
1411 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1414 if (!openFileWrite(ofs, fname))
1417 writeLyXHTMLSource(ofs, runparams, body_only);
1421 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1425 void Buffer::writeLyXHTMLSource(odocstream & os,
1426 OutputParams const & runparams,
1427 bool const only_body) const
1429 LaTeXFeatures features(*this, params(), runparams);
1431 updateLabels(UpdateMaster, true);
1436 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1437 os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n";
1438 // FIXME Language should be set properly.
1439 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1442 // FIXME Presumably need to set this right
1443 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1444 // FIXME Get this during validation? What about other meta-data?
1445 os << "<title>TBA</title>\n";
1447 os << "\n<!-- Text Class Preamble -->\n"
1448 << features.getTClassHTMLPreamble()
1449 << "\n<!-- Premable Snippets -->\n"
1450 << from_utf8(features.getPreambleSnippets());
1452 os << "\n<!-- Layout-provided Styles -->\n";
1453 docstring const styleinfo = features.getTClassHTMLStyles();
1454 if (!styleinfo.empty()) {
1455 os << "<style type='text/css'>\n"
1459 os << "</head>\n<body>\n";
1463 params().documentClass().counters().reset();
1464 xhtmlParagraphs(text(), *this, xs, runparams);
1466 os << "</body>\n</html>\n";
1470 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1471 // Other flags: -wall -v0 -x
1472 int Buffer::runChktex()
1476 // get LaTeX-Filename
1477 FileName const path(temppath());
1478 string const name = addName(path.absFilename(), latexName());
1479 string const org_path = filePath();
1481 PathChanger p(path); // path to LaTeX file
1482 message(_("Running chktex..."));
1484 // Generate the LaTeX file if neccessary
1485 OutputParams runparams(¶ms().encoding());
1486 runparams.flavor = OutputParams::LATEX;
1487 runparams.nice = false;
1488 makeLaTeXFile(FileName(name), org_path, runparams);
1491 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1492 int const res = chktex.run(terr); // run chktex
1495 Alert::error(_("chktex failure"),
1496 _("Could not run chktex successfully."));
1497 } else if (res > 0) {
1498 ErrorList & errlist = d->errorLists["ChkTeX"];
1500 bufferErrors(terr, errlist);
1511 void Buffer::validate(LaTeXFeatures & features) const
1513 params().validate(features);
1517 for_each(paragraphs().begin(), paragraphs().end(),
1518 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1520 if (lyxerr.debugging(Debug::LATEX)) {
1521 features.showStruct();
1526 void Buffer::getLabelList(vector<docstring> & list) const
1528 // If this is a child document, use the parent's list instead.
1529 Buffer const * const pbuf = d->parent();
1531 pbuf->getLabelList(list);
1536 Toc & toc = d->toc_backend.toc("label");
1537 TocIterator toc_it = toc.begin();
1538 TocIterator end = toc.end();
1539 for (; toc_it != end; ++toc_it) {
1540 if (toc_it->depth() == 0)
1541 list.push_back(toc_it->str());
1546 void Buffer::updateBibfilesCache(UpdateScope scope) const
1548 // If this is a child document, use the parent's cache instead.
1549 Buffer const * const pbuf = d->parent();
1550 if (pbuf && scope != UpdateChildOnly) {
1551 pbuf->updateBibfilesCache();
1555 d->bibfilesCache_.clear();
1556 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1557 if (it->lyxCode() == BIBTEX_CODE) {
1558 InsetBibtex const & inset =
1559 static_cast<InsetBibtex const &>(*it);
1560 support::FileNameList const bibfiles = inset.getBibFiles();
1561 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1564 } else if (it->lyxCode() == INCLUDE_CODE) {
1565 InsetInclude & inset =
1566 static_cast<InsetInclude &>(*it);
1567 inset.updateBibfilesCache();
1568 support::FileNameList const & bibfiles =
1569 inset.getBibfilesCache();
1570 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1575 // the bibinfo cache is now invalid
1576 d->bibinfoCacheValid_ = false;
1580 void Buffer::invalidateBibinfoCache()
1582 d->bibinfoCacheValid_ = false;
1586 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1588 // If this is a child document, use the parent's cache instead.
1589 Buffer const * const pbuf = d->parent();
1590 if (pbuf && scope != UpdateChildOnly)
1591 return pbuf->getBibfilesCache();
1593 // We update the cache when first used instead of at loading time.
1594 if (d->bibfilesCache_.empty())
1595 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1597 return d->bibfilesCache_;
1601 BiblioInfo const & Buffer::masterBibInfo() const
1603 // if this is a child document and the parent is already loaded
1604 // use the parent's list instead [ale990412]
1605 Buffer const * const tmp = masterBuffer();
1608 return tmp->masterBibInfo();
1609 return localBibInfo();
1613 BiblioInfo const & Buffer::localBibInfo() const
1615 if (d->bibinfoCacheValid_) {
1616 support::FileNameList const & bibfilesCache = getBibfilesCache();
1617 // compare the cached timestamps with the actual ones.
1618 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1619 support::FileNameList::const_iterator en = bibfilesCache.end();
1620 for (; ei != en; ++ ei) {
1621 time_t lastw = ei->lastModified();
1622 if (lastw != d->bibfileStatus_[*ei]) {
1623 d->bibinfoCacheValid_ = false;
1624 d->bibfileStatus_[*ei] = lastw;
1630 if (!d->bibinfoCacheValid_) {
1631 d->bibinfo_.clear();
1632 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1633 it->fillWithBibKeys(d->bibinfo_, it);
1634 d->bibinfoCacheValid_ = true;
1640 bool Buffer::isDepClean(string const & name) const
1642 DepClean::const_iterator const it = d->dep_clean.find(name);
1643 if (it == d->dep_clean.end())
1649 void Buffer::markDepClean(string const & name)
1651 d->dep_clean[name] = true;
1655 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1658 // FIXME? if there is an Buffer LFUN that can be dispatched even
1659 // if internal, put a switch '(cmd.action)' here.
1665 switch (cmd.action) {
1667 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1668 flag.setOnOff(isReadonly());
1671 // FIXME: There is need for a command-line import.
1672 //case LFUN_BUFFER_IMPORT:
1674 case LFUN_BUFFER_AUTO_SAVE:
1677 case LFUN_BUFFER_EXPORT_CUSTOM:
1678 // FIXME: Nothing to check here?
1681 case LFUN_BUFFER_EXPORT: {
1682 docstring const arg = cmd.argument();
1683 enable = arg == "custom" || isExportable(to_utf8(arg));
1685 flag.message(bformat(
1686 _("Don't know how to export to format: %1$s"), arg));
1690 case LFUN_MASTER_BUFFER_UPDATE:
1691 case LFUN_MASTER_BUFFER_VIEW:
1692 enable = parent() != 0;
1694 case LFUN_BUFFER_UPDATE:
1695 case LFUN_BUFFER_VIEW: {
1696 string format = to_utf8(cmd.argument());
1697 if (cmd.argument().empty())
1698 format = getDefaultOutputFormat();
1699 typedef vector<Format const *> Formats;
1701 formats = exportableFormats(true);
1702 Formats::const_iterator fit = formats.begin();
1703 Formats::const_iterator end = formats.end();
1705 for (; fit != end ; ++fit) {
1706 if ((*fit)->name() == format)
1711 case LFUN_BUFFER_CHKTEX:
1712 enable = isLatex() && !lyxrc.chktex_command.empty();
1715 case LFUN_BUILD_PROGRAM:
1716 enable = isExportable("program");
1719 case LFUN_BRANCH_ACTIVATE:
1720 case LFUN_BRANCH_DEACTIVATE: {
1721 BranchList const & branchList = params().branchlist();
1722 docstring const branchName = cmd.argument();
1723 enable = !branchName.empty() && branchList.find(branchName);
1727 case LFUN_BRANCH_ADD:
1728 case LFUN_BRANCHES_RENAME:
1729 case LFUN_BUFFER_PRINT:
1730 // if no Buffer is present, then of course we won't be called!
1733 case LFUN_BUFFER_LANGUAGE:
1734 enable = !isReadonly();
1740 flag.setEnabled(enable);
1745 void Buffer::dispatch(string const & command, DispatchResult & result)
1747 return dispatch(lyxaction.lookupFunc(command), result);
1751 // NOTE We can end up here even if we have no GUI, because we are called
1752 // by LyX::exec to handled command-line requests. So we may need to check
1753 // whether we have a GUI or not. The boolean use_gui holds this information.
1754 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1757 // FIXME? if there is an Buffer LFUN that can be dispatched even
1758 // if internal, put a switch '(cmd.action)' here.
1759 dr.dispatched(false);
1762 string const argument = to_utf8(func.argument());
1763 // We'll set this back to false if need be.
1764 bool dispatched = true;
1765 undo().beginUndoGroup();
1767 switch (func.action) {
1768 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1769 if (lyxvc().inUse())
1770 lyxvc().toggleReadOnly();
1772 setReadonly(!isReadonly());
1775 case LFUN_BUFFER_EXPORT: {
1776 if (argument == "custom") {
1777 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
1780 bool success = doExport(argument, false);
1781 dr.setError(success);
1783 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1788 case LFUN_BUFFER_UPDATE: {
1789 string format = argument;
1790 if (argument.empty())
1791 format = getDefaultOutputFormat();
1792 doExport(format, true);
1796 case LFUN_BUFFER_VIEW: {
1797 string format = argument;
1798 if (argument.empty())
1799 format = getDefaultOutputFormat();
1804 case LFUN_MASTER_BUFFER_UPDATE: {
1805 string format = argument;
1806 if (argument.empty())
1807 format = masterBuffer()->getDefaultOutputFormat();
1808 masterBuffer()->doExport(format, true);
1812 case LFUN_MASTER_BUFFER_VIEW: {
1813 string format = argument;
1814 if (argument.empty())
1815 format = masterBuffer()->getDefaultOutputFormat();
1816 masterBuffer()->preview(format);
1820 case LFUN_BUILD_PROGRAM:
1821 doExport("program", true);
1824 case LFUN_BUFFER_CHKTEX:
1828 case LFUN_BUFFER_EXPORT_CUSTOM: {
1830 string command = split(argument, format_name, ' ');
1831 Format const * format = formats.getFormat(format_name);
1833 lyxerr << "Format \"" << format_name
1834 << "\" not recognized!"
1839 // The name of the file created by the conversion process
1842 // Output to filename
1843 if (format->name() == "lyx") {
1844 string const latexname = latexName(false);
1845 filename = changeExtension(latexname,
1846 format->extension());
1847 filename = addName(temppath(), filename);
1849 if (!writeFile(FileName(filename)))
1853 doExport(format_name, true, filename);
1856 // Substitute $$FName for filename
1857 if (!contains(command, "$$FName"))
1858 command = "( " + command + " ) < $$FName";
1859 command = subst(command, "$$FName", filename);
1861 // Execute the command in the background
1863 call.startscript(Systemcall::DontWait, command);
1867 // FIXME: There is need for a command-line import.
1869 case LFUN_BUFFER_IMPORT:
1874 case LFUN_BUFFER_AUTO_SAVE:
1878 case LFUN_BRANCH_ADD: {
1879 docstring const branch_name = func.argument();
1880 if (branch_name.empty()) {
1884 BranchList & branch_list = params().branchlist();
1885 Branch * branch = branch_list.find(branch_name);
1887 LYXERR0("Branch " << branch_name << " already exists.");
1889 docstring const msg =
1890 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1893 branch_list.add(branch_name);
1894 branch = branch_list.find(branch_name);
1895 string const x11hexname = X11hexname(branch->color());
1896 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1897 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1899 dr.update(Update::Force);
1904 case LFUN_BRANCH_ACTIVATE:
1905 case LFUN_BRANCH_DEACTIVATE: {
1906 BranchList & branchList = params().branchlist();
1907 docstring const branchName = func.argument();
1908 // the case without a branch name is handled elsewhere
1909 if (branchName.empty()) {
1913 Branch * branch = branchList.find(branchName);
1915 LYXERR0("Branch " << branchName << " does not exist.");
1917 docstring const msg =
1918 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1921 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1923 dr.update(Update::Force);
1928 case LFUN_BRANCHES_RENAME: {
1929 if (func.argument().empty())
1932 docstring const oldname = from_utf8(func.getArg(0));
1933 docstring const newname = from_utf8(func.getArg(1));
1934 InsetIterator it = inset_iterator_begin(inset());
1935 InsetIterator const end = inset_iterator_end(inset());
1936 bool success = false;
1937 for (; it != end; ++it) {
1938 if (it->lyxCode() == BRANCH_CODE) {
1939 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1940 if (ins.branch() == oldname) {
1941 undo().recordUndo(it);
1942 ins.rename(newname);
1947 if (it->lyxCode() == INCLUDE_CODE) {
1948 // get buffer of external file
1949 InsetInclude const & ins =
1950 static_cast<InsetInclude const &>(*it);
1951 Buffer * child = ins.getChildBuffer();
1954 child->dispatch(func, dr);
1959 dr.update(Update::Force);
1963 case LFUN_BUFFER_PRINT: {
1964 // we'll assume there's a problem until we succeed
1966 string target = func.getArg(0);
1967 string target_name = func.getArg(1);
1968 string command = func.getArg(2);
1971 || target_name.empty()
1972 || command.empty()) {
1973 LYXERR0("Unable to parse " << func.argument());
1974 docstring const msg =
1975 bformat(_("Unable to parse \"%1$s\""), func.argument());
1979 if (target != "printer" && target != "file") {
1980 LYXERR0("Unrecognized target \"" << target << '"');
1981 docstring const msg =
1982 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1987 if (!doExport("dvi", true)) {
1988 showPrintError(absFileName());
1989 dr.setMessage(_("Error exporting to DVI."));
1993 // Push directory path.
1994 string const path = temppath();
1995 // Prevent the compiler from optimizing away p
1999 // there are three cases here:
2000 // 1. we print to a file
2001 // 2. we print directly to a printer
2002 // 3. we print using a spool command (print to file first)
2005 string const dviname = changeExtension(latexName(true), "dvi");
2007 if (target == "printer") {
2008 if (!lyxrc.print_spool_command.empty()) {
2009 // case 3: print using a spool
2010 string const psname = changeExtension(dviname,".ps");
2011 command += ' ' + lyxrc.print_to_file
2014 + quoteName(dviname);
2016 string command2 = lyxrc.print_spool_command + ' ';
2017 if (target_name != "default") {
2018 command2 += lyxrc.print_spool_printerprefix
2022 command2 += quoteName(psname);
2024 // If successful, then spool command
2025 res = one.startscript(Systemcall::Wait, command);
2028 // If there's no GUI, we have to wait on this command. Otherwise,
2029 // LyX deletes the temporary directory, and with it the spooled
2030 // file, before it can be printed!!
2031 Systemcall::Starttype stype = use_gui ?
2032 Systemcall::DontWait : Systemcall::Wait;
2033 res = one.startscript(stype, command2);
2036 // case 2: print directly to a printer
2037 if (target_name != "default")
2038 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2040 Systemcall::Starttype stype = use_gui ?
2041 Systemcall::DontWait : Systemcall::Wait;
2042 res = one.startscript(stype, command + quoteName(dviname));
2046 // case 1: print to a file
2047 FileName const filename(makeAbsPath(target_name, filePath()));
2048 FileName const dvifile(makeAbsPath(dviname, path));
2049 if (filename.exists()) {
2050 docstring text = bformat(
2051 _("The file %1$s already exists.\n\n"
2052 "Do you want to overwrite that file?"),
2053 makeDisplayPath(filename.absFilename()));
2054 if (Alert::prompt(_("Overwrite file?"),
2055 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2058 command += ' ' + lyxrc.print_to_file
2059 + quoteName(filename.toFilesystemEncoding())
2061 + quoteName(dvifile.toFilesystemEncoding());
2063 Systemcall::Starttype stype = use_gui ?
2064 Systemcall::DontWait : Systemcall::Wait;
2065 res = one.startscript(stype, command);
2071 dr.setMessage(_("Error running external commands."));
2072 showPrintError(absFileName());
2077 case LFUN_BUFFER_LANGUAGE: {
2078 Language const * oldL = params().language;
2079 Language const * newL = languages.getLanguage(argument);
2080 if (!newL || oldL == newL)
2082 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2083 changeLanguage(oldL, newL);
2091 dr.dispatched(dispatched);
2092 undo().endUndoGroup();
2096 void Buffer::changeLanguage(Language const * from, Language const * to)
2098 LASSERT(from, /**/);
2101 for_each(par_iterator_begin(),
2103 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2107 bool Buffer::isMultiLingual() const
2109 ParConstIterator end = par_iterator_end();
2110 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2111 if (it->isMultiLingual(params()))
2118 DocIterator Buffer::getParFromID(int const id) const
2120 Buffer * buf = const_cast<Buffer *>(this);
2122 // John says this is called with id == -1 from undo
2123 lyxerr << "getParFromID(), id: " << id << endl;
2124 return doc_iterator_end(buf);
2127 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2128 if (it.paragraph().id() == id)
2131 return doc_iterator_end(buf);
2135 bool Buffer::hasParWithID(int const id) const
2137 return !getParFromID(id).atEnd();
2141 ParIterator Buffer::par_iterator_begin()
2143 return ParIterator(doc_iterator_begin(this));
2147 ParIterator Buffer::par_iterator_end()
2149 return ParIterator(doc_iterator_end(this));
2153 ParConstIterator Buffer::par_iterator_begin() const
2155 return ParConstIterator(doc_iterator_begin(this));
2159 ParConstIterator Buffer::par_iterator_end() const
2161 return ParConstIterator(doc_iterator_end(this));
2165 Language const * Buffer::language() const
2167 return params().language;
2171 docstring const Buffer::B_(string const & l10n) const
2173 return params().B_(l10n);
2177 bool Buffer::isClean() const
2179 return d->lyx_clean;
2183 bool Buffer::isBakClean() const
2185 return d->bak_clean;
2189 bool Buffer::isExternallyModified(CheckMethod method) const
2191 LASSERT(d->filename.exists(), /**/);
2192 // if method == timestamp, check timestamp before checksum
2193 return (method == checksum_method
2194 || d->timestamp_ != d->filename.lastModified())
2195 && d->checksum_ != d->filename.checksum();
2199 void Buffer::saveCheckSum(FileName const & file) const
2201 if (file.exists()) {
2202 d->timestamp_ = file.lastModified();
2203 d->checksum_ = file.checksum();
2205 // in the case of save to a new file.
2212 void Buffer::markClean() const
2214 if (!d->lyx_clean) {
2215 d->lyx_clean = true;
2218 // if the .lyx file has been saved, we don't need an
2220 d->bak_clean = true;
2224 void Buffer::markBakClean() const
2226 d->bak_clean = true;
2230 void Buffer::setUnnamed(bool flag)
2236 bool Buffer::isUnnamed() const
2243 /// Don't check unnamed, here: isInternal() is used in
2244 /// newBuffer(), where the unnamed flag has not been set by anyone
2245 /// yet. Also, for an internal buffer, there should be no need for
2246 /// retrieving fileName() nor for checking if it is unnamed or not.
2247 bool Buffer::isInternal() const
2249 return fileName().extension() == "internal";
2253 void Buffer::markDirty()
2256 d->lyx_clean = false;
2259 d->bak_clean = false;
2261 DepClean::iterator it = d->dep_clean.begin();
2262 DepClean::const_iterator const end = d->dep_clean.end();
2264 for (; it != end; ++it)
2269 FileName Buffer::fileName() const
2275 string Buffer::absFileName() const
2277 return d->filename.absFilename();
2281 string Buffer::filePath() const
2283 return d->filename.onlyPath().absFilename() + "/";
2287 bool Buffer::isReadonly() const
2289 return d->read_only;
2293 void Buffer::setParent(Buffer const * buffer)
2295 // Avoids recursive include.
2296 d->setParent(buffer == this ? 0 : buffer);
2301 Buffer const * Buffer::parent() const
2307 void Buffer::collectRelatives(BufferSet & bufs) const
2311 parent()->collectRelatives(bufs);
2313 // loop over children
2314 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2315 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2316 for (; it != end; ++it)
2317 bufs.insert(const_cast<Buffer *>(it->first));
2321 std::vector<Buffer const *> Buffer::allRelatives() const
2324 collectRelatives(bufs);
2325 BufferSet::iterator it = bufs.begin();
2326 std::vector<Buffer const *> ret;
2327 for (; it != bufs.end(); ++it)
2333 Buffer const * Buffer::masterBuffer() const
2335 Buffer const * const pbuf = d->parent();
2339 return pbuf->masterBuffer();
2343 bool Buffer::isChild(Buffer * child) const
2345 return d->children_positions.find(child) != d->children_positions.end();
2349 DocIterator Buffer::firstChildPosition(Buffer const * child)
2351 Impl::BufferPositionMap::iterator it;
2352 it = d->children_positions.find(child);
2353 if (it == d->children_positions.end())
2354 return DocIterator(this);
2359 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2361 std::vector<Buffer *> clist;
2362 // loop over children
2363 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2364 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2365 for (; it != end; ++it) {
2366 Buffer * child = const_cast<Buffer *>(it->first);
2367 clist.push_back(child);
2368 if (grand_children) {
2369 // there might be grandchildren
2370 std::vector<Buffer *> glist = child->getChildren();
2371 for (vector<Buffer *>::const_iterator git = glist.begin();
2372 git != glist.end(); ++git)
2373 clist.push_back(*git);
2380 template<typename M>
2381 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2386 typename M::iterator it = m.lower_bound(x);
2387 if (it == m.begin())
2395 MacroData const * Buffer::getBufferMacro(docstring const & name,
2396 DocIterator const & pos) const
2398 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2400 // if paragraphs have no macro context set, pos will be empty
2404 // we haven't found anything yet
2405 DocIterator bestPos = par_iterator_begin();
2406 MacroData const * bestData = 0;
2408 // find macro definitions for name
2409 Impl::NamePositionScopeMacroMap::iterator nameIt
2410 = d->macros.find(name);
2411 if (nameIt != d->macros.end()) {
2412 // find last definition in front of pos or at pos itself
2413 Impl::PositionScopeMacroMap::const_iterator it
2414 = greatest_below(nameIt->second, pos);
2415 if (it != nameIt->second.end()) {
2417 // scope ends behind pos?
2418 if (pos < it->second.first) {
2419 // Looks good, remember this. If there
2420 // is no external macro behind this,
2421 // we found the right one already.
2422 bestPos = it->first;
2423 bestData = &it->second.second;
2427 // try previous macro if there is one
2428 if (it == nameIt->second.begin())
2435 // find macros in included files
2436 Impl::PositionScopeBufferMap::const_iterator it
2437 = greatest_below(d->position_to_children, pos);
2438 if (it == d->position_to_children.end())
2439 // no children before
2443 // do we know something better (i.e. later) already?
2444 if (it->first < bestPos )
2447 // scope ends behind pos?
2448 if (pos < it->second.first) {
2449 // look for macro in external file
2450 d->macro_lock = true;
2451 MacroData const * data
2452 = it->second.second->getMacro(name, false);
2453 d->macro_lock = false;
2455 bestPos = it->first;
2461 // try previous file if there is one
2462 if (it == d->position_to_children.begin())
2467 // return the best macro we have found
2472 MacroData const * Buffer::getMacro(docstring const & name,
2473 DocIterator const & pos, bool global) const
2478 // query buffer macros
2479 MacroData const * data = getBufferMacro(name, pos);
2483 // If there is a master buffer, query that
2484 Buffer const * const pbuf = d->parent();
2486 d->macro_lock = true;
2487 MacroData const * macro = pbuf->getMacro(
2488 name, *this, false);
2489 d->macro_lock = false;
2495 data = MacroTable::globalMacros().get(name);
2504 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2506 // set scope end behind the last paragraph
2507 DocIterator scope = par_iterator_begin();
2508 scope.pit() = scope.lastpit() + 1;
2510 return getMacro(name, scope, global);
2514 MacroData const * Buffer::getMacro(docstring const & name,
2515 Buffer const & child, bool global) const
2517 // look where the child buffer is included first
2518 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2519 if (it == d->children_positions.end())
2522 // check for macros at the inclusion position
2523 return getMacro(name, it->second, global);
2527 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2529 pit_type lastpit = it.lastpit();
2531 // look for macros in each paragraph
2532 while (it.pit() <= lastpit) {
2533 Paragraph & par = it.paragraph();
2535 // iterate over the insets of the current paragraph
2536 InsetList const & insets = par.insetList();
2537 InsetList::const_iterator iit = insets.begin();
2538 InsetList::const_iterator end = insets.end();
2539 for (; iit != end; ++iit) {
2540 it.pos() = iit->pos;
2542 // is it a nested text inset?
2543 if (iit->inset->asInsetText()) {
2544 // Inset needs its own scope?
2545 InsetText const * itext = iit->inset->asInsetText();
2546 bool newScope = itext->isMacroScope();
2548 // scope which ends just behind the inset
2549 DocIterator insetScope = it;
2552 // collect macros in inset
2553 it.push_back(CursorSlice(*iit->inset));
2554 updateMacros(it, newScope ? insetScope : scope);
2559 // is it an external file?
2560 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2561 // get buffer of external file
2562 InsetInclude const & inset =
2563 static_cast<InsetInclude const &>(*iit->inset);
2564 d->macro_lock = true;
2565 Buffer * child = inset.getChildBuffer();
2566 d->macro_lock = false;
2570 // register its position, but only when it is
2571 // included first in the buffer
2572 if (d->children_positions.find(child) ==
2573 d->children_positions.end())
2574 d->children_positions[child] = it;
2576 // register child with its scope
2577 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2581 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2585 MathMacroTemplate & macroTemplate =
2586 static_cast<MathMacroTemplate &>(*iit->inset);
2587 MacroContext mc(this, it);
2588 macroTemplate.updateToContext(mc);
2591 bool valid = macroTemplate.validMacro();
2592 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2593 // then the BufferView's cursor will be invalid in
2594 // some cases which leads to crashes.
2599 // FIXME (Abdel), I don't understandt why we pass 'it' here
2600 // instead of 'macroTemplate' defined above... is this correct?
2601 d->macros[macroTemplate.name()][it] =
2602 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2612 void Buffer::updateMacros() const
2617 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2619 // start with empty table
2621 d->children_positions.clear();
2622 d->position_to_children.clear();
2624 // Iterate over buffer, starting with first paragraph
2625 // The scope must be bigger than any lookup DocIterator
2626 // later. For the global lookup, lastpit+1 is used, hence
2627 // we use lastpit+2 here.
2628 DocIterator it = par_iterator_begin();
2629 DocIterator outerScope = it;
2630 outerScope.pit() = outerScope.lastpit() + 2;
2631 updateMacros(it, outerScope);
2635 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2637 InsetIterator it = inset_iterator_begin(inset());
2638 InsetIterator const end = inset_iterator_end(inset());
2639 for (; it != end; ++it) {
2640 if (it->lyxCode() == BRANCH_CODE) {
2641 InsetBranch & br = static_cast<InsetBranch &>(*it);
2642 docstring const name = br.branch();
2643 if (!from_master && !params().branchlist().find(name))
2644 result.push_back(name);
2645 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2646 result.push_back(name);
2649 if (it->lyxCode() == INCLUDE_CODE) {
2650 // get buffer of external file
2651 InsetInclude const & ins =
2652 static_cast<InsetInclude const &>(*it);
2653 Buffer * child = ins.getChildBuffer();
2656 child->getUsedBranches(result, true);
2659 // remove duplicates
2664 void Buffer::updateMacroInstances() const
2666 LYXERR(Debug::MACROS, "updateMacroInstances for "
2667 << d->filename.onlyFileName());
2668 DocIterator it = doc_iterator_begin(this);
2670 DocIterator const end = doc_iterator_end(this);
2671 for (; it != end; it.forwardInset()) {
2672 // look for MathData cells in InsetMathNest insets
2673 InsetMath * minset = it.nextInset()->asInsetMath();
2677 // update macro in all cells of the InsetMathNest
2678 DocIterator::idx_type n = minset->nargs();
2679 MacroContext mc = MacroContext(this, it);
2680 for (DocIterator::idx_type i = 0; i < n; ++i) {
2681 MathData & data = minset->cell(i);
2682 data.updateMacros(0, mc);
2688 void Buffer::listMacroNames(MacroNameSet & macros) const
2693 d->macro_lock = true;
2695 // loop over macro names
2696 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2697 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2698 for (; nameIt != nameEnd; ++nameIt)
2699 macros.insert(nameIt->first);
2701 // loop over children
2702 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2703 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2704 for (; it != end; ++it)
2705 it->first->listMacroNames(macros);
2708 Buffer const * const pbuf = d->parent();
2710 pbuf->listMacroNames(macros);
2712 d->macro_lock = false;
2716 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2718 Buffer const * const pbuf = d->parent();
2723 pbuf->listMacroNames(names);
2726 MacroNameSet::iterator it = names.begin();
2727 MacroNameSet::iterator end = names.end();
2728 for (; it != end; ++it) {
2730 MacroData const * data =
2731 pbuf->getMacro(*it, *this, false);
2733 macros.insert(data);
2735 // we cannot access the original MathMacroTemplate anymore
2736 // here to calls validate method. So we do its work here manually.
2737 // FIXME: somehow make the template accessible here.
2738 if (data->optionals() > 0)
2739 features.require("xargs");
2745 Buffer::References & Buffer::references(docstring const & label)
2748 return const_cast<Buffer *>(masterBuffer())->references(label);
2750 RefCache::iterator it = d->ref_cache_.find(label);
2751 if (it != d->ref_cache_.end())
2752 return it->second.second;
2754 static InsetLabel const * dummy_il = 0;
2755 static References const dummy_refs;
2756 it = d->ref_cache_.insert(
2757 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2758 return it->second.second;
2762 Buffer::References const & Buffer::references(docstring const & label) const
2764 return const_cast<Buffer *>(this)->references(label);
2768 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2770 masterBuffer()->d->ref_cache_[label].first = il;
2774 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2776 return masterBuffer()->d->ref_cache_[label].first;
2780 void Buffer::clearReferenceCache() const
2783 d->ref_cache_.clear();
2787 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2790 //FIXME: This does not work for child documents yet.
2791 LASSERT(code == CITE_CODE, /**/);
2792 // Check if the label 'from' appears more than once
2793 vector<docstring> labels;
2795 BiblioInfo const & keys = masterBibInfo();
2796 BiblioInfo::const_iterator bit = keys.begin();
2797 BiblioInfo::const_iterator bend = keys.end();
2799 for (; bit != bend; ++bit)
2801 labels.push_back(bit->first);
2804 if (count(labels.begin(), labels.end(), from) > 1)
2807 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2808 if (it->lyxCode() == code) {
2809 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2810 docstring const oldValue = inset.getParam(paramName);
2811 if (oldValue == from)
2812 inset.setParam(paramName, to);
2818 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2819 pit_type par_end, bool full_source) const
2821 OutputParams runparams(¶ms().encoding());
2822 runparams.nice = true;
2823 runparams.flavor = params().useXetex ?
2824 OutputParams::XETEX : OutputParams::LATEX;
2825 runparams.linelen = lyxrc.plaintext_linelen;
2826 // No side effect of file copying and image conversion
2827 runparams.dryrun = true;
2830 os << "% " << _("Preview source code") << "\n\n";
2832 d->texrow.newline();
2833 d->texrow.newline();
2835 writeDocBookSource(os, absFileName(), runparams, false);
2837 // latex or literate
2838 writeLaTeXSource(os, string(), runparams, true, true);
2840 runparams.par_begin = par_begin;
2841 runparams.par_end = par_end;
2842 if (par_begin + 1 == par_end) {
2844 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2848 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2849 convert<docstring>(par_begin),
2850 convert<docstring>(par_end - 1))
2857 // output paragraphs
2859 docbookParagraphs(text(), *this, os, runparams);
2861 // latex or literate
2862 latexParagraphs(*this, text(), os, texrow, runparams);
2867 ErrorList & Buffer::errorList(string const & type) const
2869 static ErrorList emptyErrorList;
2870 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2871 if (I == d->errorLists.end())
2872 return emptyErrorList;
2878 void Buffer::updateTocItem(std::string const & type,
2879 DocIterator const & dit) const
2882 gui_->updateTocItem(type, dit);
2886 void Buffer::structureChanged() const
2889 gui_->structureChanged();
2893 void Buffer::errors(string const & err, bool from_master) const
2896 gui_->errors(err, from_master);
2900 void Buffer::message(docstring const & msg) const
2907 void Buffer::setBusy(bool on) const
2914 void Buffer::setReadOnly(bool on) const
2917 d->wa_->setReadOnly(on);
2921 void Buffer::updateTitles() const
2924 d->wa_->updateTitles();
2928 void Buffer::resetAutosaveTimers() const
2931 gui_->resetAutosaveTimers();
2935 bool Buffer::hasGuiDelegate() const
2941 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2950 class AutoSaveBuffer : public ForkedProcess {
2953 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2954 : buffer_(buffer), fname_(fname) {}
2956 virtual boost::shared_ptr<ForkedProcess> clone() const
2958 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2963 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2964 from_utf8(fname_.absFilename())));
2965 return run(DontWait);
2969 virtual int generateChild();
2971 Buffer const & buffer_;
2976 int AutoSaveBuffer::generateChild()
2978 #if defined(__APPLE__)
2979 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
2980 * We should use something else like threads.
2982 * Since I do not know how to determine at run time what is the OS X
2983 * version, I just disable forking altogether for now (JMarc)
2985 pid_t const pid = -1;
2987 // tmp_ret will be located (usually) in /tmp
2988 // will that be a problem?
2989 // Note that this calls ForkedCalls::fork(), so it's
2990 // ok cross-platform.
2991 pid_t const pid = fork();
2992 // If you want to debug the autosave
2993 // you should set pid to -1, and comment out the fork.
2994 if (pid != 0 && pid != -1)
2998 // pid = -1 signifies that lyx was unable
2999 // to fork. But we will do the save
3001 bool failed = false;
3002 FileName const tmp_ret = FileName::tempName("lyxauto");
3003 if (!tmp_ret.empty()) {
3004 buffer_.writeFile(tmp_ret);
3005 // assume successful write of tmp_ret
3006 if (!tmp_ret.moveTo(fname_))
3012 // failed to write/rename tmp_ret so try writing direct
3013 if (!buffer_.writeFile(fname_)) {
3014 // It is dangerous to do this in the child,
3015 // but safe in the parent, so...
3016 if (pid == -1) // emit message signal.
3017 buffer_.message(_("Autosave failed!"));
3021 if (pid == 0) // we are the child so...
3030 FileName Buffer::getAutosaveFilename() const
3032 // if the document is unnamed try to save in the backup dir, else
3033 // in the default document path, and as a last try in the filePath,
3034 // which will most often be the temporary directory
3037 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3038 : lyxrc.backupdir_path;
3039 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3042 string const fname = "#" + d->filename.onlyFileName() + "#";
3043 return makeAbsPath(fname, fpath);
3047 void Buffer::removeAutosaveFile() const
3049 FileName const f = getAutosaveFilename();
3055 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3057 FileName const newauto = getAutosaveFilename();
3058 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3059 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3063 // Perfect target for a thread...
3064 void Buffer::autoSave() const
3066 if (isBakClean() || isReadonly()) {
3067 // We don't save now, but we'll try again later
3068 resetAutosaveTimers();
3072 // emit message signal.
3073 message(_("Autosaving current document..."));
3074 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3078 resetAutosaveTimers();
3082 string Buffer::bufferFormat() const
3084 string format = params().documentClass().outputFormat();
3085 if (format == "latex") {
3086 if (params().useXetex)
3088 if (params().encoding().package() == Encoding::japanese)
3095 string Buffer::getDefaultOutputFormat() const
3097 if (!params().defaultOutputFormat.empty()
3098 && params().defaultOutputFormat != "default")
3099 return params().defaultOutputFormat;
3100 typedef vector<Format const *> Formats;
3101 Formats formats = exportableFormats(true);
3104 || params().useXetex
3105 || params().encoding().package() == Encoding::japanese) {
3106 if (formats.empty())
3108 // return the first we find
3109 return formats.front()->name();
3111 return lyxrc.default_view_format;
3116 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3117 string & result_file) const
3119 string backend_format;
3120 OutputParams runparams(¶ms().encoding());
3121 runparams.flavor = OutputParams::LATEX;
3122 runparams.linelen = lyxrc.plaintext_linelen;
3123 vector<string> backs = backends();
3124 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3125 // Get shortest path to format
3126 Graph::EdgePath path;
3127 for (vector<string>::const_iterator it = backs.begin();
3128 it != backs.end(); ++it) {
3129 Graph::EdgePath p = theConverters().getPath(*it, format);
3130 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3131 backend_format = *it;
3136 runparams.flavor = theConverters().getFlavor(path);
3138 Alert::error(_("Couldn't export file"),
3139 bformat(_("No information for exporting the format %1$s."),
3140 formats.prettyName(format)));
3144 backend_format = format;
3145 // FIXME: Don't hardcode format names here, but use a flag
3146 if (backend_format == "pdflatex")
3147 runparams.flavor = OutputParams::PDFLATEX;
3150 string filename = latexName(false);
3151 filename = addName(temppath(), filename);
3152 filename = changeExtension(filename,
3153 formats.extension(backend_format));
3156 updateMacroInstances();
3158 // Plain text backend
3159 if (backend_format == "text") {
3160 runparams.flavor = OutputParams::TEXT;
3161 writePlaintextFile(*this, FileName(filename), runparams);
3164 else if (backend_format == "xhtml") {
3165 runparams.flavor = OutputParams::HTML;
3166 makeLyXHTMLFile(FileName(filename), runparams);
3167 } else if (backend_format == "lyx")
3168 writeFile(FileName(filename));
3170 else if (isDocBook()) {
3171 runparams.nice = !put_in_tempdir;
3172 makeDocBookFile(FileName(filename), runparams);
3175 else if (backend_format == format) {
3176 runparams.nice = true;
3177 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3179 } else if (!lyxrc.tex_allows_spaces
3180 && contains(filePath(), ' ')) {
3181 Alert::error(_("File name error"),
3182 _("The directory path to the document cannot contain spaces."));
3185 runparams.nice = false;
3186 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3190 string const error_type = (format == "program")
3191 ? "Build" : bufferFormat();
3192 ErrorList & error_list = d->errorLists[error_type];
3193 string const ext = formats.extension(format);
3194 FileName const tmp_result_file(changeExtension(filename, ext));
3195 bool const success = theConverters().convert(this, FileName(filename),
3196 tmp_result_file, FileName(absFileName()), backend_format, format,
3198 // Emit the signal to show the error list.
3199 if (format != backend_format) {
3201 // also to the children, in case of master-buffer-view
3202 std::vector<Buffer *> clist = getChildren();
3203 for (vector<Buffer *>::const_iterator cit = clist.begin();
3204 cit != clist.end(); ++cit)
3205 (*cit)->errors(error_type, true);
3210 if (put_in_tempdir) {
3211 result_file = tmp_result_file.absFilename();
3215 result_file = changeExtension(exportFileName().absFilename(), ext);
3216 // We need to copy referenced files (e. g. included graphics
3217 // if format == "dvi") to the result dir.
3218 vector<ExportedFile> const files =
3219 runparams.exportdata->externalFiles(format);
3220 string const dest = onlyPath(result_file);
3221 CopyStatus status = SUCCESS;
3222 for (vector<ExportedFile>::const_iterator it = files.begin();
3223 it != files.end() && status != CANCEL; ++it) {
3224 string const fmt = formats.getFormatFromFile(it->sourceName);
3225 status = copyFile(fmt, it->sourceName,
3226 makeAbsPath(it->exportName, dest),
3227 it->exportName, status == FORCE);
3229 if (status == CANCEL) {
3230 message(_("Document export cancelled."));
3231 } else if (tmp_result_file.exists()) {
3232 // Finally copy the main file
3233 status = copyFile(format, tmp_result_file,
3234 FileName(result_file), result_file,
3236 message(bformat(_("Document exported as %1$s "
3238 formats.prettyName(format),
3239 makeDisplayPath(result_file)));
3241 // This must be a dummy converter like fax (bug 1888)
3242 message(bformat(_("Document exported as %1$s"),
3243 formats.prettyName(format)));
3250 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3253 return doExport(format, put_in_tempdir, result_file);
3257 bool Buffer::preview(string const & format) const
3260 if (!doExport(format, true, result_file))
3262 return formats.view(*this, FileName(result_file), format);
3266 bool Buffer::isExportable(string const & format) const
3268 vector<string> backs = backends();
3269 for (vector<string>::const_iterator it = backs.begin();
3270 it != backs.end(); ++it)
3271 if (theConverters().isReachable(*it, format))
3277 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3279 vector<string> const backs = backends();
3280 vector<Format const *> result =
3281 theConverters().getReachable(backs[0], only_viewable, true);
3282 for (vector<string>::const_iterator it = backs.begin() + 1;
3283 it != backs.end(); ++it) {
3284 vector<Format const *> r =
3285 theConverters().getReachable(*it, only_viewable, false);
3286 result.insert(result.end(), r.begin(), r.end());
3292 vector<string> Buffer::backends() const
3295 v.push_back(bufferFormat());
3296 // FIXME: Don't hardcode format names here, but use a flag
3297 if (v.back() == "latex")
3298 v.push_back("pdflatex");
3299 v.push_back("xhtml");
3300 v.push_back("text");
3306 bool Buffer::readFileHelper(FileName const & s)
3308 // File information about normal file
3310 docstring const file = makeDisplayPath(s.absFilename(), 50);
3311 docstring text = bformat(_("The specified document\n%1$s"
3312 "\ncould not be read."), file);
3313 Alert::error(_("Could not read document"), text);
3317 // Check if emergency save file exists and is newer.
3318 FileName const e(s.absFilename() + ".emergency");
3320 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3321 docstring const file = makeDisplayPath(s.absFilename(), 20);
3322 docstring const text =
3323 bformat(_("An emergency save of the document "
3325 "Recover emergency save?"), file);
3326 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3327 _("&Recover"), _("&Load Original"),
3331 // the file is not saved if we load the emergency file.
3336 if ((res = readFile(e)) == success)
3337 str = _("Document was successfully recovered.");
3339 str = _("Document was NOT successfully recovered.");
3340 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3341 from_utf8(e.absFilename()));
3343 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3344 _("&Remove"), _("&Keep it"))) {
3347 Alert::warning(_("Emergency file deleted"),
3348 _("Do not forget to save your file now!"), true);
3353 if (!Alert::prompt(_("Delete emergency file?"),
3354 _("Remove emergency file now?"), 1, 1,
3355 _("&Remove"), _("&Keep it")))
3363 // Now check if autosave file is newer.
3364 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3366 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3367 docstring const file = makeDisplayPath(s.absFilename(), 20);
3368 docstring const text =
3369 bformat(_("The backup of the document "
3370 "%1$s is newer.\n\nLoad the "
3371 "backup instead?"), file);
3372 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3373 _("&Load backup"), _("Load &original"),
3377 // the file is not saved if we load the autosave file.
3381 // Here we delete the autosave
3392 bool Buffer::loadLyXFile(FileName const & s)
3394 if (s.isReadableFile()) {
3395 if (readFileHelper(s)) {
3396 lyxvc().file_found_hook(s);
3397 if (!s.isWritable())
3402 docstring const file = makeDisplayPath(s.absFilename(), 20);
3403 // Here we probably should run
3404 if (LyXVC::file_not_found_hook(s)) {
3405 docstring const text =
3406 bformat(_("Do you want to retrieve the document"
3407 " %1$s from version control?"), file);
3408 int const ret = Alert::prompt(_("Retrieve from version control?"),
3409 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3412 // How can we know _how_ to do the checkout?
3413 // With the current VC support it has to be,
3414 // a RCS file since CVS do not have special ,v files.
3416 return loadLyXFile(s);
3424 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3426 TeXErrors::Errors::const_iterator cit = terr.begin();
3427 TeXErrors::Errors::const_iterator end = terr.end();
3429 for (; cit != end; ++cit) {
3432 int errorRow = cit->error_in_line;
3433 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3439 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3440 } while (found && id_start == id_end && pos_start == pos_end);
3442 errorList.push_back(ErrorItem(cit->error_desc,
3443 cit->error_text, id_start, pos_start, pos_end));
3448 void Buffer::setBuffersForInsets() const
3450 inset().setBuffer(const_cast<Buffer &>(*this));
3454 void Buffer::updateLabels(UpdateScope scope, bool out) const
3456 // Use the master text class also for child documents
3457 Buffer const * const master = masterBuffer();
3458 DocumentClass const & textclass = master->params().documentClass();
3460 // keep the buffers to be children in this set. If the call from the
3461 // master comes back we can see which of them were actually seen (i.e.
3462 // via an InsetInclude). The remaining ones in the set need still be updated.
3463 static std::set<Buffer const *> bufToUpdate;
3464 if (scope == UpdateMaster) {
3465 // If this is a child document start with the master
3466 if (master != this) {
3467 bufToUpdate.insert(this);
3468 master->updateLabels(UpdateMaster, out);
3469 // Do this here in case the master has no gui associated with it. Then,
3470 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3474 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3475 if (bufToUpdate.find(this) == bufToUpdate.end())
3479 // start over the counters in the master
3480 textclass.counters().reset();
3483 // update will be done below for this buffer
3484 bufToUpdate.erase(this);
3486 // update all caches
3487 clearReferenceCache();
3490 Buffer & cbuf = const_cast<Buffer &>(*this);
3492 LASSERT(!text().paragraphs().empty(), /**/);
3495 ParIterator parit = cbuf.par_iterator_begin();
3496 updateLabels(parit, out);
3499 // TocBackend update will be done later.
3502 cbuf.tocBackend().update();
3503 if (scope == UpdateMaster)
3504 cbuf.structureChanged();
3508 static depth_type getDepth(DocIterator const & it)
3510 depth_type depth = 0;
3511 for (size_t i = 0 ; i < it.depth() ; ++i)
3512 if (!it[i].inset().inMathed())
3513 depth += it[i].paragraph().getDepth() + 1;
3514 // remove 1 since the outer inset does not count
3518 static depth_type getItemDepth(ParIterator const & it)
3520 Paragraph const & par = *it;
3521 LabelType const labeltype = par.layout().labeltype;
3523 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3526 // this will hold the lowest depth encountered up to now.
3527 depth_type min_depth = getDepth(it);
3528 ParIterator prev_it = it;
3531 --prev_it.top().pit();
3533 // start of nested inset: go to outer par
3535 if (prev_it.empty()) {
3536 // start of document: nothing to do
3541 // We search for the first paragraph with same label
3542 // that is not more deeply nested.
3543 Paragraph & prev_par = *prev_it;
3544 depth_type const prev_depth = getDepth(prev_it);
3545 if (labeltype == prev_par.layout().labeltype) {
3546 if (prev_depth < min_depth)
3547 return prev_par.itemdepth + 1;
3548 if (prev_depth == min_depth)
3549 return prev_par.itemdepth;
3551 min_depth = min(min_depth, prev_depth);
3552 // small optimization: if we are at depth 0, we won't
3553 // find anything else
3554 if (prev_depth == 0)
3560 static bool needEnumCounterReset(ParIterator const & it)
3562 Paragraph const & par = *it;
3563 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3564 depth_type const cur_depth = par.getDepth();
3565 ParIterator prev_it = it;
3566 while (prev_it.pit()) {
3567 --prev_it.top().pit();
3568 Paragraph const & prev_par = *prev_it;
3569 if (prev_par.getDepth() <= cur_depth)
3570 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3572 // start of nested inset: reset
3577 // set the label of a paragraph. This includes the counters.
3578 void Buffer::setLabel(ParIterator & it) const
3580 BufferParams const & bp = this->masterBuffer()->params();
3581 DocumentClass const & textclass = bp.documentClass();
3582 Paragraph & par = it.paragraph();
3583 Layout const & layout = par.layout();
3584 Counters & counters = textclass.counters();
3586 if (par.params().startOfAppendix()) {
3587 // FIXME: only the counter corresponding to toplevel
3588 // sectioning should be reset
3590 counters.appendix(true);
3592 par.params().appendix(counters.appendix());
3594 // Compute the item depth of the paragraph
3595 par.itemdepth = getItemDepth(it);
3597 if (layout.margintype == MARGIN_MANUAL
3598 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3599 if (par.params().labelWidthString().empty())
3600 par.params().labelWidthString(par.expandLabel(layout, bp));
3602 par.params().labelWidthString(docstring());
3605 switch(layout.labeltype) {
3607 if (layout.toclevel <= bp.secnumdepth
3608 && (layout.latextype != LATEX_ENVIRONMENT
3609 || it.text()->isFirstInSequence(it.pit()))) {
3610 counters.step(layout.counter);
3611 par.params().labelString(
3612 par.expandLabel(layout, bp));
3614 par.params().labelString(docstring());
3617 case LABEL_ITEMIZE: {
3618 // At some point of time we should do something more
3619 // clever here, like:
3620 // par.params().labelString(
3621 // bp.user_defined_bullet(par.itemdepth).getText());
3622 // for now, use a simple hardcoded label
3623 docstring itemlabel;
3624 switch (par.itemdepth) {
3626 itemlabel = char_type(0x2022);
3629 itemlabel = char_type(0x2013);
3632 itemlabel = char_type(0x2217);
3635 itemlabel = char_type(0x2219); // or 0x00b7
3638 par.params().labelString(itemlabel);
3642 case LABEL_ENUMERATE: {
3643 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3645 switch (par.itemdepth) {
3654 enumcounter += "iv";
3657 // not a valid enumdepth...
3661 // Maybe we have to reset the enumeration counter.
3662 if (needEnumCounterReset(it))
3663 counters.reset(enumcounter);
3664 counters.step(enumcounter);
3666 string const & lang = par.getParLanguage(bp)->code();
3667 par.params().labelString(counters.theCounter(enumcounter, lang));
3672 case LABEL_SENSITIVE: {
3673 string const & type = counters.current_float();
3674 docstring full_label;
3676 full_label = this->B_("Senseless!!! ");
3678 docstring name = this->B_(textclass.floats().getType(type).name());
3679 if (counters.hasCounter(from_utf8(type))) {
3680 string const & lang = par.getParLanguage(bp)->code();
3681 counters.step(from_utf8(type));
3682 full_label = bformat(from_ascii("%1$s %2$s:"),
3684 counters.theCounter(from_utf8(type), lang));
3686 full_label = bformat(from_ascii("%1$s #:"), name);
3688 par.params().labelString(full_label);
3692 case LABEL_NO_LABEL:
3693 par.params().labelString(docstring());
3697 case LABEL_TOP_ENVIRONMENT:
3698 case LABEL_CENTERED_TOP_ENVIRONMENT:
3701 par.params().labelString(par.expandLabel(layout, bp));
3707 void Buffer::updateLabels(ParIterator & parit, bool out) const
3709 LASSERT(parit.pit() == 0, /**/);
3711 // set the position of the text in the buffer to be able
3712 // to resolve macros in it. This has nothing to do with
3713 // labels, but by putting it here we avoid implementing
3714 // a whole bunch of traversal routines just for this call.
3715 parit.text()->setMacrocontextPosition(parit);
3717 depth_type maxdepth = 0;
3718 pit_type const lastpit = parit.lastpit();
3719 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3720 // reduce depth if necessary
3721 parit->params().depth(min(parit->params().depth(), maxdepth));
3722 maxdepth = parit->getMaxDepthAfter();
3724 // set the counter for this paragraph
3728 InsetList::const_iterator iit = parit->insetList().begin();
3729 InsetList::const_iterator end = parit->insetList().end();
3730 for (; iit != end; ++iit) {
3731 parit.pos() = iit->pos;
3732 iit->inset->updateLabels(parit, out);
3738 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3739 WordLangTuple & word_lang, docstring_list & suggestions) const
3743 suggestions.clear();
3744 word_lang = WordLangTuple();
3745 // OK, we start from here.
3746 DocIterator const end = doc_iterator_end(this);
3747 for (; from != end; from.forwardPos()) {
3748 // We are only interested in text so remove the math CursorSlice.
3749 while (from.inMathed()) {
3753 // If from is at the end of the document (which is possible
3754 // when leaving the mathed) LyX will crash later.
3758 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3763 // Do not increase progress when from == to, otherwise the word
3764 // count will be wrong.