4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
7 * \author Lars Gullik Bjønnes
9 * Full author contact details are available in file CREDITS.
15 #include "OutputEnums.h"
17 #include "insets/InsetCode.h"
19 #include "support/strfwd.h"
20 #include "support/types.h"
53 class ParConstIterator;
63 class GuiBufferDelegate;
64 class WorkAreaManager;
74 typedef std::list<Buffer *> ListOfBuffers;
77 /** The buffer object.
78 * This is the buffer object. It contains all the informations about
79 * a document loaded into LyX.
80 * The buffer object owns the Text (wrapped in an InsetText), which
81 * contains the individual paragraphs of the document.
84 * I am not sure if the class is complete or
85 * minimal, probably not.
86 * \author Lars Gullik Bjønnes
90 /// What type of log will \c getLogName() return?
92 latexlog, ///< LaTeX log
93 buildlog ///< Literate build log
96 /// Result of \c readFile()
106 ReadEmergencyFailure,
119 /// Method to check if a file is externally modified, used by
120 /// isExternallyModified()
122 * timestamp is fast but inaccurate. For example, the granularity
123 * of timestamp on a FAT filesystem is 2 second. Also, various operations
124 * may touch the timestamp of a file even when its content is unchanged.
126 * checksum is accurate but slow, which can be a problem when it is
127 * frequently used, or used for a large file on a slow (network) file
130 * FIXME: replace this method with support/FileMonitor.
133 checksum_method, ///< Use file checksum
134 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
144 explicit Buffer(std::string const & file, bool readonly = false,
145 Buffer const * cloned_buffer = 0);
151 Buffer * clone() const;
153 bool isClone() const;
155 /** High-level interface to buffer functionality.
156 This function parses a command string and executes it.
158 void dispatch(std::string const & command, DispatchResult & result);
160 /// Maybe we know the function already by number...
161 void dispatch(FuncRequest const & func, DispatchResult & result);
163 /// Can this function be exectued?
164 /// \return true if we made a decision
165 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
168 DocIterator getParFromID(int id) const;
169 /// do we have a paragraph with this id?
170 bool hasParWithID(int id) const;
173 frontend::WorkAreaManager & workAreaManager() const;
176 Takes care of auto-save files and backup file if requested.
177 Returns \c true if the save is successful, \c false otherwise.
180 /// Renames and saves the buffer
181 bool saveAs(support::FileName const & fn);
183 /// Write document to stream. Returns \c false if unsuccesful.
184 bool write(std::ostream &) const;
185 /// Write file. Returns \c false if unsuccesful.
186 bool writeFile(support::FileName const &) const;
188 /// \name Functions involved in reading files/strings.
190 /// Loads the LyX file into the buffer. This function
191 /// tries to extract the file from version control if it
192 /// cannot be found. If it can be found, it will try to
193 /// read an emergency save file or an autosave file.
194 /// \sa loadThisLyXFile
195 ReadStatus loadLyXFile();
196 /// Loads the LyX file \c fn into the buffer. If you want
197 /// to check for files in a version control container,
198 /// emergency or autosave files, one should use \c loadLyXFile.
200 ReadStatus loadThisLyXFile(support::FileName const & fn);
201 /// read a new document from a string
202 bool readString(std::string const &);
203 /// Reloads the LyX file
205 //FIXME: The following two functions should be private
207 /// read the header, returns number of unknown tokens
208 int readHeader(Lexer & lex);
209 /// save timestamp and checksum of the given file.
210 void saveCheckSum() const;
214 ReadStatus readFile(support::FileName const & fn);
215 /// Reads a file without header.
216 /// \param par if != 0 insert the file.
217 /// \return \c true if file is not completely read.
218 bool readDocument(Lexer &);
219 /// Try to extract the file from a version control container
220 /// before reading if the file cannot be found. This is only
221 /// implemented for RCS.
222 /// \sa LyXVC::file_not_found_hook
223 ReadStatus extractFromVC();
224 /// Reads the first tag of a LyX File and
225 /// returns the file format number.
226 ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
227 int & file_format) const;
228 /// Convert the LyX file to the LYX_FORMAT using
229 /// the lyx2lyx script and returns the filename
230 /// of the temporary file to be read
231 ReadStatus convertLyXFormat(support::FileName const & fn,
232 support::FileName & tmpfile, int from_format);
236 /// \name Functions involved in autosave and emergency files.
239 void autoSave() const;
240 /// save emergency file
241 /// \return a status message towards the user.
242 docstring emergencyWrite();
244 //FIXME:The following three functions should be private
247 void removeAutosaveFile() const;
249 void moveAutosaveFile(support::FileName const & old) const;
250 /// Get the filename of the autosave file associated with the Buffer
251 support::FileName getAutosaveFileName() const;
254 /// Try to load an autosave file associated to \c fn.
255 ReadStatus loadAutosave();
256 /// Try to load an emergency file associated to \c fn.
257 ReadStatus loadEmergency();
258 /// Get the filename of the emergency file associated with the Buffer
259 support::FileName getEmergencyFileName() const;
263 /// Fill in the ErrorList with the TeXErrors
264 void bufferErrors(TeXErrors const &, ErrorList &) const;
266 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
267 bool makeLaTeXFile(support::FileName const & filename,
268 std::string const & original_path,
269 OutputParams const &,
270 bool output_preamble = true,
271 bool output_body = true) const;
272 /** Export the buffer to LaTeX.
273 If \p os is a file stream, and params().inputenc is "auto" or
274 "default", and the buffer contains text in different languages
275 with more than one encoding, then this method will change the
276 encoding associated to \p os. Therefore you must not call this
277 method with a string stream if the output is supposed to go to a
280 ofs.open("test.tex");
281 writeLaTeXSource(ofs, ...);
283 \endcode is NOT equivalent to \code
284 odocstringstream oss;
285 writeLaTeXSource(oss, ...);
287 ofs.open("test.tex");
292 void writeLaTeXSource(odocstream & os,
293 std::string const & original_path,
294 OutputParams const &,
295 bool output_preamble = true,
296 bool output_body = true) const;
298 void makeDocBookFile(support::FileName const & filename,
299 OutputParams const & runparams_in,
300 bool only_body = false) const;
302 void writeDocBookSource(odocstream & os, std::string const & filename,
303 OutputParams const & runparams_in,
304 bool only_body = false) const;
306 void makeLyXHTMLFile(support::FileName const & filename,
307 OutputParams const & runparams_in,
308 bool only_body = false) const;
310 void writeLyXHTMLSource(odocstream & os,
311 OutputParams const & runparams_in,
312 bool only_body = false) const;
313 /// returns the main language for the buffer (document)
314 Language const * language() const;
315 /// get l10n translated to the buffers language
316 docstring const B_(std::string const & l10n) const;
320 /// return true if the main lyx file does not need saving
321 bool isClean() const;
323 bool isDepClean(std::string const & name) const;
325 /// whether or not disk file has been externally modified
326 bool isExternallyModified(CheckMethod method) const;
328 /// mark the main lyx file as not needing saving
329 void markClean() const;
332 void markDepClean(std::string const & name);
335 void setUnnamed(bool flag = true);
337 /// Whether or not a filename has been assigned to this buffer
338 bool isUnnamed() const;
340 /// Whether or not this buffer is internal.
342 /// An internal buffer does not contain a real document, but some auxiliary text segment.
343 /// It is not associated with a filename, it is never saved, thus it does not need to be
344 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
345 bool isInternal() const;
347 /// Mark this buffer as dirty.
350 /// Returns the buffer's filename. It is always an absolute path.
351 support::FileName fileName() const;
353 /// Returns the buffer's filename. It is always an absolute path.
354 std::string absFileName() const;
356 /// Returns the the path where the buffer lives.
357 /// It is always an absolute path.
358 std::string filePath() const;
360 /** A transformed version of the file name, adequate for LaTeX.
361 \param no_path optional if \c true then the path is stripped.
363 std::string latexName(bool no_path = true) const;
365 /// Get the name and type of the log.
366 std::string logName(LogType * type = 0) const;
368 /// Change name of buffer. Updates "read-only" flag.
369 void setFileName(std::string const & newfile);
371 /// Set document's parent Buffer.
372 void setParent(Buffer const *);
373 Buffer const * parent() const;
375 /** Get the document's master (or \c this if this is not a
378 Buffer const * masterBuffer() const;
380 /// \return true if \p child is a child of this \c Buffer.
381 bool isChild(Buffer * child) const;
383 /// \return true if this \c Buffer has children
384 bool hasChildren() const;
386 /// \return a list of the direct children of this Buffer.
387 /// this list has no duplicates and is in the order in which
388 /// the children appear.
389 ListOfBuffers getChildren() const;
391 /// \return a list of all descendents of this Buffer (children,
392 /// grandchildren, etc). this list has no duplicates and is in
393 /// the order in which the children appear.
394 ListOfBuffers getDescendents() const;
396 /// Collect all relative buffers, in the order in which they appear.
397 /// I.e., the "root" Buffer is first, then its first child, then any
398 /// of its children, etc. However, there are no duplicates in this
400 /// This is "stable", too, in the sense that it returns the same
401 /// thing from whichever Buffer it is called.
402 ListOfBuffers allRelatives() const;
404 /// Is buffer read-only?
405 bool isReadonly() const;
407 /// Set buffer read-only flag
408 void setReadonly(bool flag = true);
410 /// returns \c true if the buffer contains a LaTeX document
411 bool isLatex() const;
412 /// returns \c true if the buffer contains a DocBook document
413 bool isDocBook() const;
414 /// returns \c true if the buffer contains a Wed document
415 bool isLiterate() const;
417 /** Validate a buffer for LaTeX.
418 This validates the buffer, and returns a struct for use by
419 #makeLaTeX# and others. Its main use is to figure out what
420 commands and packages need to be included in the LaTeX file.
421 It (should) also check that the needed constructs are there
422 (i.e. that the \refs points to coresponding \labels). It
423 should perhaps inset "error" insets to help the user correct
426 void validate(LaTeXFeatures &) const;
428 /// Reference information is cached in the Buffer, so we do not
429 /// have to check or read things over and over.
431 /// There are two caches.
433 /// One is a cache of the BibTeX files from which reference info is
434 /// being gathered. This cache is PER BUFFER, and the cache for the
435 /// master essentially includes the cache for its children. This gets
436 /// invalidated when an InsetBibtex is created, deleted, or modified.
438 /// The other is a cache of the reference information itself. This
439 /// exists only in the master buffer, and when it needs to be updated,
440 /// the children add their information to the master's cache.
442 /// Calling this method invalidates the cache and so requires a
444 void invalidateBibinfoCache() const;
445 /// This invalidates the cache of files we need to check.
446 void invalidateBibfileCache() const;
447 /// Updates the cached bibliography information.
448 /// Note that you MUST call this method to update the cache. It will
449 /// not happen otherwise. (Currently, it is called at the start of
450 /// updateBuffer() and from GuiCitation.)
451 /// Note that this operates on the master document.
452 void checkBibInfoCache() const;
453 /// \return the bibliography information for this buffer's master,
454 /// or just for it, if it isn't a child.
455 BiblioInfo const & masterBibInfo() const;
457 void fillWithBibKeys(BiblioInfo & keys) const;
459 void getLabelList(std::vector<docstring> &) const;
462 void changeLanguage(Language const * from, Language const * to);
465 bool isMultiLingual() const;
467 std::set<Language const *> getLanguages() const;
470 BufferParams & params();
471 BufferParams const & params() const;
473 /** The list of paragraphs.
474 This is a linked list of paragraph, this list holds the
475 whole contents of the document.
477 ParagraphList & paragraphs();
478 ParagraphList const & paragraphs() const;
480 /// LyX version control object.
482 LyXVC const & lyxvc() const;
484 /// Where to put temporary files.
485 std::string const temppath() const;
487 /// Used when typesetting to place errorboxes.
488 TexRow const & texrow() const;
492 ParIterator par_iterator_begin();
494 ParConstIterator par_iterator_begin() const;
496 ParIterator par_iterator_end();
498 ParConstIterator par_iterator_end() const;
500 // Position of the child buffer where it appears first in the master.
501 DocIterator firstChildPosition(Buffer const * child);
503 /** \returns true only when the file is fully loaded.
504 * Used to prevent the premature generation of previews
505 * and by the citation inset.
507 bool isFullyLoaded() const;
508 /// Set by buffer_funcs' newFile.
509 void setFullyLoaded(bool);
511 /// Update the LaTeX preview snippets associated with this buffer
512 void updatePreviews() const;
513 /// Remove any previewed LaTeX snippets associated with this buffer
514 void removePreviews() const;
516 /// Our main text (inside the top InsetText)
519 /// Our top InsetText
520 Inset & inset() const;
525 /// Collect macro definitions in paragraphs
526 void updateMacros() const;
527 /// Iterate through the whole buffer and try to resolve macros
528 void updateMacroInstances() const;
530 /// List macro names of this buffer, the parent and the children
531 void listMacroNames(MacroNameSet & macros) const;
532 /// Collect macros of the parent and its children in front of this buffer.
533 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
535 /// Return macro defined before pos (or in the master buffer)
536 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
537 /// Return macro defined anywhere in the buffer (or in the master buffer)
538 MacroData const * getMacro(docstring const & name, bool global = true) const;
539 /// Return macro defined before the inclusion of the child
540 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
542 /// Collect user macro names at loading time
543 typedef std::set<docstring> UserMacroSet;
544 UserMacroSet usermacros;
546 /// Replace the inset contents for insets which InsetCode is equal
547 /// to the passed \p inset_code.
548 void changeRefsIfUnique(docstring const & from, docstring const & to,
551 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
552 /// including preamble
553 void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
554 bool full_source) const;
556 /// Access to error list.
557 /// This method is used only for GUI visualisation of Buffer related
558 /// errors (like parsing or LateX compilation). This method is const
559 /// because modifying the returned ErrorList does not touch the document
561 ErrorList & errorList(std::string const & type) const;
564 /// This is useful only for screen visualisation of the Buffer. This
565 /// method is const because modifying this backend does not touch
566 /// the document contents.
567 TocBackend & tocBackend() const;
572 /// This function is called when the buffer is changed.
573 void changed(bool update_metrics) const;
575 void setChild(DocIterator const & dit, Buffer * child);
577 void updateTocItem(std::string const &, DocIterator const &) const;
578 /// This function is called when the buffer structure is changed.
579 void structureChanged() const;
580 /// This function is called when some parsing error shows up.
581 void errors(std::string const & err, bool from_master = false) const;
582 /// This function is called when the buffer busy status change.
583 void setBusy(bool on) const;
584 /// Update window titles of all users.
585 void updateTitles() const;
586 /// Reset autosave timers for all users.
587 void resetAutosaveTimers() const;
589 void message(docstring const & msg) const;
592 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
594 bool hasGuiDelegate() const;
598 /// return the format of the buffer on a string
599 std::string bufferFormat() const;
600 /// return the default output format of the current backend
601 std::string getDefaultOutputFormat() const;
604 bool doExport(std::string const & format, bool put_in_tempdir,
605 bool includeall, std::string & result_file) const;
607 bool doExport(std::string const & format, bool put_in_tempdir,
608 bool includeall = false) const;
610 bool preview(std::string const & format, bool includeall = false) const;
612 bool isExportable(std::string const & format) const;
614 std::vector<Format const *> exportableFormats(bool only_viewable) const;
616 bool isExportableFormat(std::string const & format) const;
617 /// mark the buffer as busy exporting something, or not
618 void setExportStatus(bool e) const;
620 bool isExporting() const;
623 typedef std::vector<std::pair<Inset *, ParIterator> > References;
624 References & references(docstring const & label);
625 References const & references(docstring const & label) const;
626 void clearReferenceCache() const;
627 void setInsetLabel(docstring const & label, InsetLabel const * il);
628 InsetLabel const * insetLabel(docstring const & label) const;
630 /// return a list of all used branches (also in children)
631 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
633 /// sets the buffer_ member for every inset in this buffer.
634 // FIXME This really shouldn't be needed, but at the moment it's not
635 // clear how to do it just for the individual pieces we need.
636 void setBuffersForInsets() const;
637 /// Updates screen labels and some other information associated with
638 /// insets and paragraphs. Actually, it's more like a general "recurse
639 /// through the Buffer" routine, that visits all the insets and paragraphs.
640 void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
641 /// \param scope: whether to start with the master document or just
643 /// \param output: whether we are preparing for output.
644 void updateBuffer(UpdateScope scope, UpdateType utype) const;
646 void updateBuffer(ParIterator & parit, UpdateType utype) const;
648 /// Spellcheck starting from \p from.
649 /// \p from initial position, will then points to the next misspelled
651 /// \p to will points to the end of the next misspelled word.
652 /// \p word_lang will contain the found misspelled word.
653 /// \return progress if a new word was found.
654 int spellCheck(DocIterator & from, DocIterator & to,
655 WordLangTuple & word_lang, docstring_list & suggestions) const;
657 void checkChildBuffers();
661 std::vector<std::string> backends() const;
663 void getLanguages(std::set<Language const *> &) const;
664 /// Update the list of all bibfiles in use (including bibfiles
665 /// of loaded child documents).
666 void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
667 /// Return the list with all bibfiles in use (including bibfiles
668 /// of loaded child documents).
669 support::FileNameList const &
670 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
672 void collectChildren(ListOfBuffers & children, bool grand_children) const;
675 /// Use the Pimpl idiom to hide the internals.
677 /// The pointer never changes although *pimpl_'s contents may.