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"
16 #include "OutputParams.h"
18 #include "insets/InsetCode.h"
20 #include "support/strfwd.h"
21 #include "support/types.h"
56 class ParConstIterator;
66 class GuiBufferDelegate;
67 class WorkAreaManager;
81 typedef std::list<Buffer *> ListOfBuffers;
84 /** The buffer object.
85 * This is the buffer object. It contains all the informations about
86 * a document loaded into LyX.
87 * The buffer object owns the Text (wrapped in an InsetText), which
88 * contains the individual paragraphs of the document.
91 * I am not sure if the class is complete or
92 * minimal, probably not.
93 * \author Lars Gullik Bjønnes
97 /// What type of log will \c getLogName() return?
99 latexlog, ///< LaTeX log
100 buildlog ///< Literate build log
103 /// Result of \c readFile()
113 ReadEmergencyFailure,
128 ExportNoPathToFormat,
129 ExportTexPathHasSpaces,
133 /// Method to check if a file is externally modified, used by
134 /// isExternallyModified()
136 * timestamp is fast but inaccurate. For example, the granularity
137 * of timestamp on a FAT filesystem is 2 second. Also, various operations
138 * may touch the timestamp of a file even when its content is unchanged.
140 * checksum is accurate but slow, which can be a problem when it is
141 * frequently used, or used for a large file on a slow (network) file
144 * FIXME: replace this method with support/FileMonitor.
147 checksum_method, ///< Use file checksum
148 timestamp_method ///< Use timestamp, and checksum if timestamp has changed
158 explicit Buffer(std::string const & file, bool readonly = false,
159 Buffer const * cloned_buffer = 0);
165 Buffer * clone() const;
167 bool isClone() const;
169 /** High-level interface to buffer functionality.
170 This function parses a command string and executes it.
172 void dispatch(std::string const & command, DispatchResult & result);
174 /// Maybe we know the function already by number...
175 void dispatch(FuncRequest const & func, DispatchResult & result);
177 /// Can this function be exectued?
178 /// \return true if we made a decision
179 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
182 DocIterator getParFromID(int id) const;
183 /// do we have a paragraph with this id?
184 bool hasParWithID(int id) const;
187 frontend::WorkAreaManager & workAreaManager() const;
190 Takes care of auto-save files and backup file if requested.
191 Returns \c true if the save is successful, \c false otherwise.
194 /// Renames and saves the buffer
195 bool saveAs(support::FileName const & fn);
197 /// Write document to stream. Returns \c false if unsuccessful.
198 bool write(std::ostream &) const;
199 /// Write file. Returns \c false if unsuccessful.
200 bool writeFile(support::FileName const &) const;
202 /// \name Functions involved in reading files/strings.
204 /// Loads the LyX file into the buffer. This function
205 /// tries to extract the file from version control if it
206 /// cannot be found. If it can be found, it will try to
207 /// read an emergency save file or an autosave file.
208 /// \sa loadThisLyXFile
209 ReadStatus loadLyXFile();
210 /// Loads the LyX file \c fn into the buffer. If you want
211 /// to check for files in a version control container,
212 /// emergency or autosave files, one should use \c loadLyXFile.
214 ReadStatus loadThisLyXFile(support::FileName const & fn);
215 /// read a new document from a string
216 bool readString(std::string const &);
217 /// Reloads the LyX file
219 //FIXME: The following function should be private
221 /// read the header, returns number of unknown tokens
222 int readHeader(Lexer & lex);
226 typedef std::map<Buffer const *, Buffer *> BufferMap;
228 void clone(BufferMap &) const;
229 /// save timestamp and checksum of the given file.
230 void saveCheckSum() const;
232 ReadStatus readFile(support::FileName const & fn);
233 /// Reads a file without header.
234 /// \param par if != 0 insert the file.
235 /// \return \c true if file is not completely read.
236 bool readDocument(Lexer &);
237 /// Try to extract the file from a version control container
238 /// before reading if the file cannot be found. This is only
239 /// implemented for RCS.
240 /// \sa LyXVC::file_not_found_hook
241 ReadStatus extractFromVC();
242 /// Reads the first tag of a LyX File and
243 /// returns the file format number.
244 ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
245 int & file_format) const;
246 /// Convert the LyX file to the LYX_FORMAT using
247 /// the lyx2lyx script and returns the filename
248 /// of the temporary file to be read
249 ReadStatus convertLyXFormat(support::FileName const & fn,
250 support::FileName & tmpfile, int from_format);
254 /// \name Functions involved in autosave and emergency files.
256 /// Save an autosave file to #filename.lyx#
257 bool autoSave() const;
258 /// save emergency file
259 /// \return a status message towards the user.
260 docstring emergencyWrite();
262 //FIXME:The following function should be private
265 void removeAutosaveFile() const;
268 /// Try to load an autosave file associated to \c fn.
269 ReadStatus loadAutosave();
270 /// Try to load an emergency file associated to \c fn.
271 ReadStatus loadEmergency();
272 /// Get the filename of the emergency file associated with the Buffer
273 support::FileName getEmergencyFileName() const;
274 /// Get the filename of the autosave file associated with the Buffer
275 support::FileName getAutosaveFileName() const;
277 void moveAutosaveFile(support::FileName const & old) const;
281 /// Fill in the ErrorList with the TeXErrors
282 void bufferErrors(TeXErrors const &, ErrorList &) const;
284 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
285 bool makeLaTeXFile(support::FileName const & filename,
286 std::string const & original_path,
287 OutputParams const &,
288 bool output_preamble = true,
289 bool output_body = true) const;
290 /** Export the buffer to LaTeX.
291 If \p os is a file stream, and params().inputenc is "auto" or
292 "default", and the buffer contains text in different languages
293 with more than one encoding, then this method will change the
294 encoding associated to \p os. Therefore you must not call this
295 method with a string stream if the output is supposed to go to a
298 otexstream os(ofs, texrow);
299 ofs.open("test.tex");
300 writeLaTeXSource(os, ...);
302 \endcode is NOT equivalent to \code
303 odocstringstream oss;
304 otexstream os(oss, texrow);
305 writeLaTeXSource(os, ...);
307 ofs.open("test.tex");
312 void writeLaTeXSource(otexstream & os,
313 std::string const & original_path,
314 OutputParams const &,
315 bool output_preamble = true,
316 bool output_body = true) const;
318 void makeDocBookFile(support::FileName const & filename,
319 OutputParams const & runparams_in,
320 bool only_body = false) const;
322 void writeDocBookSource(odocstream & os, std::string const & filename,
323 OutputParams const & runparams_in,
324 bool only_body = false) const;
326 void makeLyXHTMLFile(support::FileName const & filename,
327 OutputParams const & runparams_in) const;
329 void writeLyXHTMLSource(odocstream & os,
330 OutputParams const & runparams_in,
331 bool only_body = false) const;
332 /// returns the main language for the buffer (document)
333 Language const * language() const;
334 /// get l10n translated to the buffers language
335 docstring const B_(std::string const & l10n) const;
339 /// return true if the main lyx file does not need saving
340 bool isClean() const;
342 bool isDepClean(std::string const & name) const;
344 /// whether or not disk file has been externally modified
345 bool isExternallyModified(CheckMethod method) const;
347 /// mark the main lyx file as not needing saving
348 void markClean() const;
351 void markDepClean(std::string const & name);
354 void setUnnamed(bool flag = true);
356 /// Whether or not a filename has been assigned to this buffer
357 bool isUnnamed() const;
359 /// Whether or not this buffer is internal.
361 /// An internal buffer does not contain a real document, but some auxiliary text segment.
362 /// It is not associated with a filename, it is never saved, thus it does not need to be
363 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
364 bool isInternal() const;
366 /// Mark this buffer as dirty.
369 /// Returns the buffer's filename. It is always an absolute path.
370 support::FileName fileName() const;
372 /// Returns the buffer's filename. It is always an absolute path.
373 std::string absFileName() const;
375 /// Returns the the path where the buffer lives.
376 /// It is always an absolute path.
377 std::string filePath() const;
379 /** A transformed version of the file name, adequate for LaTeX.
380 \param no_path optional if \c true then the path is stripped.
382 std::string latexName(bool no_path = true) const;
384 /// Get the name and type of the log.
385 std::string logName(LogType * type = 0) const;
387 /// Set document's parent Buffer.
388 void setParent(Buffer const *);
389 Buffer const * parent() const;
391 /** Get the document's master (or \c this if this is not a
394 Buffer const * masterBuffer() const;
396 /// \return true if \p child is a child of this \c Buffer.
397 bool isChild(Buffer * child) const;
399 /// \return true if this \c Buffer has children
400 bool hasChildren() const;
402 /// \return a list of the direct children of this Buffer.
403 /// this list has no duplicates and is in the order in which
404 /// the children appear.
405 ListOfBuffers getChildren() const;
407 /// \return a list of all descendents of this Buffer (children,
408 /// grandchildren, etc). this list has no duplicates and is in
409 /// the order in which the children appear.
410 ListOfBuffers getDescendents() const;
412 /// Collect all relative buffers, in the order in which they appear.
413 /// I.e., the "root" Buffer is first, then its first child, then any
414 /// of its children, etc. However, there are no duplicates in this
416 /// This is "stable", too, in the sense that it returns the same
417 /// thing from whichever Buffer it is called.
418 ListOfBuffers allRelatives() const;
420 /// Is buffer read-only?
421 bool isReadonly() const;
423 /// Set buffer read-only flag
424 void setReadonly(bool flag = true);
426 /** Validate a buffer for LaTeX.
427 This validates the buffer, and returns a struct for use by
428 #makeLaTeX# and others. Its main use is to figure out what
429 commands and packages need to be included in the LaTeX file.
430 It (should) also check that the needed constructs are there
431 (i.e. that the \refs points to coresponding \labels). It
432 should perhaps inset "error" insets to help the user correct
435 void validate(LaTeXFeatures &) const;
437 /// Reference information is cached in the Buffer, so we do not
438 /// have to check or read things over and over.
440 /// There are two caches.
442 /// One is a cache of the BibTeX files from which reference info is
443 /// being gathered. This cache is PER BUFFER, and the cache for the
444 /// master essentially includes the cache for its children. This gets
445 /// invalidated when an InsetBibtex is created, deleted, or modified.
447 /// The other is a cache of the reference information itself. This
448 /// exists only in the master buffer, and when it needs to be updated,
449 /// the children add their information to the master's cache.
451 /// Calling this method invalidates the cache and so requires a
453 void invalidateBibinfoCache() const;
454 /// This invalidates the cache of files we need to check.
455 void invalidateBibfileCache() const;
456 /// Updates the cached bibliography information, checking first to see
457 /// whether the cache is valid. If so, we do nothing. If not, then we
458 /// reload all the BibTeX info.
459 /// Note that this operates on the master document.
460 void reloadBibInfoCache() const;
461 /// \return the bibliography information for this buffer's master,
462 /// or just for it, if it isn't a child.
463 BiblioInfo const & masterBibInfo() const;
464 /// collect bibliography info from the various insets in this buffer.
465 void collectBibKeys() const;
466 /// add some BiblioInfo to our cache
467 void addBiblioInfo(BiblioInfo const & bi) const;
468 /// add a single piece of bibliography info to our cache
469 void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
471 bool citeLabelsValid() const;
473 void getLabelList(std::vector<docstring> &) const;
476 void changeLanguage(Language const * from, Language const * to);
479 bool isMultiLingual() const;
481 std::set<Language const *> getLanguages() const;
484 BufferParams & params();
485 BufferParams const & params() const;
487 /** The list of paragraphs.
488 This is a linked list of paragraph, this list holds the
489 whole contents of the document.
491 ParagraphList & paragraphs();
492 ParagraphList const & paragraphs() const;
494 /// LyX version control object.
496 LyXVC const & lyxvc() const;
498 /// Where to put temporary files.
499 std::string const temppath() const;
501 /// Used when typesetting to place errorboxes.
502 TexRow const & texrow() const;
506 ParIterator par_iterator_begin();
508 ParConstIterator par_iterator_begin() const;
510 ParIterator par_iterator_end();
512 ParConstIterator par_iterator_end() const;
514 // Position of the child buffer where it appears first in the master.
515 DocIterator firstChildPosition(Buffer const * child);
517 /** \returns true only when the file is fully loaded.
518 * Used to prevent the premature generation of previews
519 * and by the citation inset.
521 bool isFullyLoaded() const;
522 /// Set by buffer_funcs' newFile.
523 void setFullyLoaded(bool);
525 /// FIXME: Needed by RenderPreview.
526 graphics::PreviewLoader * loader() const;
527 /// Update the LaTeX preview snippets associated with this buffer
528 void updatePreviews() const;
529 /// Remove any previewed LaTeX snippets associated with this buffer
530 void removePreviews() const;
532 /// Our main text (inside the top InsetText)
535 /// Our top InsetText
536 Inset & inset() const;
541 /// Collect macro definitions in paragraphs
542 void updateMacros() const;
543 /// Iterate through the whole buffer and try to resolve macros
544 void updateMacroInstances(UpdateType) const;
546 /// List macro names of this buffer, the parent and the children
547 void listMacroNames(MacroNameSet & macros) const;
548 /// Collect macros of the parent and its children in front of this buffer.
549 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
551 /// Return macro defined before pos (or in the master buffer)
552 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
553 /// Return macro defined anywhere in the buffer (or in the master buffer)
554 MacroData const * getMacro(docstring const & name, bool global = true) const;
555 /// Return macro defined before the inclusion of the child
556 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
558 /// Collect user macro names at loading time
559 typedef std::set<docstring> UserMacroSet;
560 mutable UserMacroSet usermacros;
562 /// Replace the inset contents for insets which InsetCode is equal
563 /// to the passed \p inset_code.
564 void changeRefsIfUnique(docstring const & from, docstring const & to,
567 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
568 /// including preamble
569 void getSourceCode(odocstream & os, std::string const format,
570 pit_type par_begin, pit_type par_end, bool full_source) const;
572 /// Access to error list.
573 /// This method is used only for GUI visualisation of Buffer related
574 /// errors (like parsing or LateX compilation). This method is const
575 /// because modifying the returned ErrorList does not touch the document
577 ErrorList & errorList(std::string const & type) const;
580 /// This is useful only for screen visualisation of the Buffer. This
581 /// method is const because modifying this backend does not touch
582 /// the document contents.
583 TocBackend & tocBackend() const;
588 /// This function is called when the buffer is changed.
589 void changed(bool update_metrics) const;
591 void setChild(DocIterator const & dit, Buffer * child);
593 void updateTocItem(std::string const &, DocIterator const &) const;
594 /// This function is called when the buffer structure is changed.
595 void structureChanged() const;
596 /// This function is called when some parsing error shows up.
597 void errors(std::string const & err, bool from_master = false) const;
598 /// This function is called when the buffer busy status change.
599 void setBusy(bool on) const;
600 /// Update window titles of all users.
601 void updateTitles() const;
602 /// Reset autosave timers for all users.
603 void resetAutosaveTimers() const;
605 void message(docstring const & msg) const;
608 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
610 bool hasGuiDelegate() const;
613 bool doExport(std::string const & target, bool put_in_tempdir) const;
615 bool preview(std::string const & format) const;
618 /// target is a format name optionally followed by a space
619 /// and a destination file-name
620 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
621 bool includeall, std::string & result_file) const;
623 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
624 bool includeall) const;
626 bool preview(std::string const & format, bool includeall = false) const;
629 /// mark the buffer as busy exporting something, or not
630 void setExportStatus(bool e) const;
632 bool isExporting() const;
635 typedef std::vector<std::pair<Inset *, ParIterator> > References;
636 References & references(docstring const & label);
637 References const & references(docstring const & label) const;
638 void clearReferenceCache() const;
639 void setInsetLabel(docstring const & label, InsetLabel const * il);
640 InsetLabel const * insetLabel(docstring const & label) const;
642 /// return a list of all used branches (also in children)
643 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
645 /// sets the buffer_ member for every inset in this buffer.
646 // FIXME This really shouldn't be needed, but at the moment it's not
647 // clear how to do it just for the individual pieces we need.
648 void setBuffersForInsets() const;
649 /// Updates screen labels and some other information associated with
650 /// insets and paragraphs. Actually, it's more like a general "recurse
651 /// through the Buffer" routine, that visits all the insets and paragraphs.
652 void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
653 /// \param scope: whether to start with the master document or just
655 /// \param output: whether we are preparing for output.
656 void updateBuffer(UpdateScope scope, UpdateType utype) const;
658 void updateBuffer(ParIterator & parit, UpdateType utype) const;
660 /// Spellcheck starting from \p from.
661 /// \p from initial position, will then points to the next misspelled
663 /// \p to will points to the end of the next misspelled word.
664 /// \p word_lang will contain the found misspelled word.
665 /// \return progress if a new word was found.
666 int spellCheck(DocIterator & from, DocIterator & to,
667 WordLangTuple & word_lang, docstring_list & suggestions) const;
669 void checkChildBuffers();
672 /// Change name of buffer. Updates "read-only" flag.
673 void setFileName(support::FileName const & fname);
675 void getLanguages(std::set<Language const *> &) const;
676 /// Checks whether any of the referenced bibfiles have changed since the
677 /// last time we loaded the cache. Note that this does NOT update the
678 /// cached information.
679 void checkIfBibInfoCacheIsValid() const;
680 /// Update the list of all bibfiles in use (including bibfiles
681 /// of loaded child documents).
682 void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
683 /// Return the list with all bibfiles in use (including bibfiles
684 /// of loaded child documents).
685 support::FileNameList const &
686 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
688 void collectChildren(ListOfBuffers & children, bool grand_children) const;
691 Buffer(Buffer const &);
692 void operator=(Buffer const &);
694 /// Use the Pimpl idiom to hide the internals.
696 /// The pointer never changes although *pimpl_'s contents may.