]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
* Add possibility to append active branch names to the output file name (#3105).
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "update_flags.h"
16
17 #include "insets/InsetCode.h"
18
19 #include "support/strfwd.h"
20 #include "support/types.h"
21 #include "support/SignalSlot.h"
22
23 #include <list>
24 #include <string>
25 #include <vector>
26
27
28 namespace lyx {
29
30 class BiblioInfo;
31 class BufferParams;
32 class BufferSet;
33 class DispatchResult;
34 class DocIterator;
35 class docstring_list;
36 class ErrorItem;
37 class ErrorList;
38 class FuncRequest;
39 class FuncStatus;
40 class Inset;
41 class InsetRef;
42 class InsetLabel;
43 class Font;
44 class Format;
45 class Lexer;
46 class LyXRC;
47 class Text;
48 class LyXVC;
49 class LaTeXFeatures;
50 class Language;
51 class MacroData;
52 class MacroNameSet;
53 class MacroSet;
54 class OutputParams;
55 class Paragraph;
56 class ParConstIterator;
57 class ParIterator;
58 class ParagraphList;
59 class TeXErrors;
60 class TexRow;
61 class TocBackend;
62 class Undo;
63 class WordLangTuple;
64
65 namespace frontend {
66 class GuiBufferDelegate;
67 class WorkAreaManager;
68 }
69
70 namespace support {
71 class FileName;
72 class FileNameList;
73 }
74
75 /** The buffer object.
76  * This is the buffer object. It contains all the informations about
77  * a document loaded into LyX.
78  * The buffer object owns the Text (wrapped in an InsetText), which
79  * contains the individual paragraphs of the document.
80  *
81  *
82  * I am not sure if the class is complete or
83  * minimal, probably not.
84  * \author Lars Gullik Bjønnes
85  */
86 class Buffer {
87 public:
88         /// What type of log will \c getLogName() return?
89         enum LogType {
90                 latexlog, ///< LaTeX log
91                 buildlog  ///< Literate build log
92         };
93
94         /// Result of \c readFile()
95         enum ReadStatus {
96                 failure, ///< The file could not be read
97                 success, ///< The file could not be read
98                 wrongversion ///< The version of the file does not match ours
99         };
100
101
102         /// Method to check if a file is externally modified, used by
103         /// isExternallyModified()
104         /**
105          * timestamp is fast but inaccurate. For example, the granularity
106          * of timestamp on a FAT filesystem is 2 second. Also, various operations
107          * may touch the timestamp of a file even when its content is unchanged.
108          *
109          * checksum is accurate but slow, which can be a problem when it is
110          * frequently used, or used for a large file on a slow (network) file
111          * system.
112          *
113          * FIXME: replace this method with support/FileMonitor.
114          */
115         enum CheckMethod {
116                 checksum_method,  ///< Use file checksum
117                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
118         };
119
120         ///
121         enum UpdateScope {
122                 UpdateMaster,
123                 UpdateChildOnly
124         };
125
126         /// Constructor
127         explicit Buffer(std::string const & file, bool b = false);
128
129         /// Destructor
130         ~Buffer();
131
132         /** High-level interface to buffer functionality.
133             This function parses a command string and executes it.
134         */
135         void dispatch(std::string const & command, DispatchResult & result);
136
137         /// Maybe we know the function already by number...
138         void dispatch(FuncRequest const & func, DispatchResult & result);
139
140         /// Can this function be exectued?
141         /// \return true if we made a decision
142         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
143
144         /// read a new document from a string
145         bool readString(std::string const &);
146         /// load a new file
147         bool readFile(support::FileName const & filename);
148
149         /// read the header, returns number of unknown tokens
150         int readHeader(Lexer & lex);
151
152         /** Reads a file without header.
153             \param par if != 0 insert the file.
154             \return \c true if file is not completely read.
155         */
156         bool readDocument(Lexer &);
157
158         ///
159         void insertStringAsLines(ParagraphList & plist,
160                 pit_type &, pos_type &,
161                 Font const &, docstring const &, bool);
162         ///
163         DocIterator getParFromID(int id) const;
164         /// do we have a paragraph with this id?
165         bool hasParWithID(int id) const;
166
167         ///
168         frontend::WorkAreaManager & workAreaManager() const;
169
170         /** Save file.
171             Takes care of auto-save files and backup file if requested.
172             Returns \c true if the save is successful, \c false otherwise.
173         */
174         bool save() const;
175
176         /// Write document to stream. Returns \c false if unsuccesful.
177         bool write(std::ostream &) const;
178         /// Write file. Returns \c false if unsuccesful.
179         bool writeFile(support::FileName const &) const;
180
181         /// Loads LyX file \c filename into buffer, *  and \return success
182         bool loadLyXFile(support::FileName const & s);
183
184         /// Fill in the ErrorList with the TeXErrors
185         void bufferErrors(TeXErrors const &, ErrorList &) const;
186
187         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
188         bool makeLaTeXFile(support::FileName const & filename,
189                            std::string const & original_path,
190                            OutputParams const &,
191                            bool output_preamble = true,
192                            bool output_body = true) const;
193         /** Export the buffer to LaTeX.
194             If \p os is a file stream, and params().inputenc is "auto" or
195             "default", and the buffer contains text in different languages
196             with more than one encoding, then this method will change the
197             encoding associated to \p os. Therefore you must not call this
198             method with a string stream if the output is supposed to go to a
199             file. \code
200             ofdocstream ofs;
201             ofs.open("test.tex");
202             writeLaTeXSource(ofs, ...);
203             ofs.close();
204             \endcode is NOT equivalent to \code
205             odocstringstream oss;
206             writeLaTeXSource(oss, ...);
207             ofdocstream ofs;
208             ofs.open("test.tex");
209             ofs << oss.str();
210             ofs.close();
211             \endcode
212          */
213         void writeLaTeXSource(odocstream & os,
214                            std::string const & original_path,
215                            OutputParams const &,
216                            bool output_preamble = true,
217                            bool output_body = true) const;
218         ///
219         void makeDocBookFile(support::FileName const & filename,
220                              OutputParams const & runparams_in,
221                              bool only_body = false) const;
222         ///
223         void writeDocBookSource(odocstream & os, std::string const & filename,
224                              OutputParams const & runparams_in,
225                              bool only_body = false) const;
226         ///
227         void makeLyXHTMLFile(support::FileName const & filename,
228                              OutputParams const & runparams_in,
229                              bool only_body = false) const;
230         ///
231         void writeLyXHTMLSource(odocstream & os,
232                              OutputParams const & runparams_in,
233                              bool only_body = false) const;
234         /// returns the main language for the buffer (document)
235         Language const * language() const;
236         /// get l10n translated to the buffers language
237         docstring const B_(std::string const & l10n) const;
238
239         ///
240         int runChktex();
241         /// return true if the main lyx file does not need saving
242         bool isClean() const;
243         ///
244         bool isBakClean() const;
245         ///
246         bool isDepClean(std::string const & name) const;
247
248         /// whether or not disk file has been externally modified
249         bool isExternallyModified(CheckMethod method) const;
250
251         /// save timestamp and checksum of the given file.
252         void saveCheckSum(support::FileName const & file) const;
253
254         /// mark the main lyx file as not needing saving
255         void markClean() const;
256
257         ///
258         void markBakClean() const;
259
260         ///
261         void markDepClean(std::string const & name);
262
263         ///
264         void setUnnamed(bool flag = true);
265
266         ///
267         bool isUnnamed() const;
268
269         /// Mark this buffer as dirty.
270         void markDirty();
271
272         /// Returns the buffer's filename. It is always an absolute path.
273         support::FileName fileName() const;
274
275         /// Returns the buffer's filename. It is always an absolute path.
276         std::string absFileName() const;
277
278         /// Returns the the path where the buffer lives.
279         /// It is always an absolute path.
280         std::string filePath() const;
281
282         /** A transformed version of the file name, adequate for LaTeX.
283             \param no_path optional if \c true then the path is stripped.
284         */
285         std::string latexName(bool no_path = true) const;
286
287         /// Get the name and type of the log.
288         std::string logName(LogType * type = 0) const;
289
290         /// Change name of buffer. Updates "read-only" flag.
291         void setFileName(std::string const & newfile);
292
293         /// Set document's parent Buffer.
294         void setParent(Buffer const *);
295         Buffer const * parent() const;
296
297         // Collect all relative buffer
298         std::vector<Buffer const *> allRelatives() const;
299
300         /** Get the document's master (or \c this if this is not a
301             child document)
302          */
303         Buffer const * masterBuffer() const;
304
305         /// \return true if \p child is a child of this \c Buffer.
306         bool isChild(Buffer * child) const;
307         
308         /// return a vector with all children and grandchildren
309         std::vector<Buffer *> getChildren() const;
310
311         /// Is buffer read-only?
312         bool isReadonly() const;
313
314         /// Set buffer read-only flag
315         void setReadonly(bool flag = true);
316
317         /// returns \c true if the buffer contains a LaTeX document
318         bool isLatex() const;
319         /// returns \c true if the buffer contains a DocBook document
320         bool isDocBook() const;
321         /// returns \c true if the buffer contains a Wed document
322         bool isLiterate() const;
323
324         /** Validate a buffer for LaTeX.
325             This validates the buffer, and returns a struct for use by
326             #makeLaTeX# and others. Its main use is to figure out what
327             commands and packages need to be included in the LaTeX file.
328             It (should) also check that the needed constructs are there
329             (i.e. that the \refs points to coresponding \labels). It
330             should perhaps inset "error" insets to help the user correct
331             obvious mistakes.
332         */
333         void validate(LaTeXFeatures &) const;
334
335         /// Update the cache with all bibfiles in use (including bibfiles
336         /// of loaded child documents).
337         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
338         ///
339         void invalidateBibinfoCache();
340         /// Return the cache with all bibfiles in use (including bibfiles
341         /// of loaded child documents).
342         support::FileNameList const & 
343                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
344         /// \return the bibliography information for this buffer's master,
345         /// or just for it, if it isn't a child.
346         BiblioInfo const & masterBibInfo() const;
347         /// \return the bibliography information for this buffer ONLY.
348         BiblioInfo const & localBibInfo() const;
349         ///
350         void getLabelList(std::vector<docstring> &) const;
351
352         ///
353         void changeLanguage(Language const * from, Language const * to);
354
355         ///
356         bool isMultiLingual() const;
357
358         ///
359         BufferParams & params();
360         BufferParams const & params() const;
361
362         /** The list of paragraphs.
363             This is a linked list of paragraph, this list holds the
364             whole contents of the document.
365          */
366         ParagraphList & paragraphs();
367         ParagraphList const & paragraphs() const;
368
369         /// LyX version control object.
370         LyXVC & lyxvc();
371         LyXVC const & lyxvc() const;
372
373         /// Where to put temporary files.
374         std::string const temppath() const;
375
376         /// Used when typesetting to place errorboxes.
377         TexRow const & texrow() const;
378         TexRow & texrow();
379
380         ///
381         ParIterator par_iterator_begin();
382         ///
383         ParConstIterator par_iterator_begin() const;
384         ///
385         ParIterator par_iterator_end();
386         ///
387         ParConstIterator par_iterator_end() const;
388
389         // Position of the child buffer where it appears first in the master.
390         DocIterator firstChildPosition(Buffer const * child);
391
392         /** \returns true only when the file is fully loaded.
393          *  Used to prevent the premature generation of previews
394          *  and by the citation inset.
395          */
396         bool isFullyLoaded() const;
397         /// Set by buffer_funcs' newFile.
398         void setFullyLoaded(bool);
399
400         /// Our main text (inside the top InsetText)
401         Text & text() const;
402
403         /// Our top InsetText
404         Inset & inset() const;
405
406         //
407         // Macro handling
408         //
409         /// Collect macro definitions in paragraphs
410         void updateMacros() const;
411         /// Iterate through the whole buffer and try to resolve macros
412         void updateMacroInstances() const;
413
414         /// List macro names of this buffer, the parent and the children
415         void listMacroNames(MacroNameSet & macros) const;
416         /// Collect macros of the parent and its children in front of this buffer.
417         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
418
419         /// Return macro defined before pos (or in the master buffer)
420         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
421         /// Return macro defined anywhere in the buffer (or in the master buffer)
422         MacroData const * getMacro(docstring const & name, bool global = true) const;
423         /// Return macro defined before the inclusion of the child
424         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
425
426         /// Replace the inset contents for insets which InsetCode is equal
427         /// to the passed \p inset_code.
428         void changeRefsIfUnique(docstring const & from, docstring const & to,
429                 InsetCode code);
430
431         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
432         /// including preamble
433         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
434                 bool full_source) const;
435
436         /// Access to error list.
437         /// This method is used only for GUI visualisation of Buffer related
438         /// errors (like parsing or LateX compilation). This method is const
439         /// because modifying the returned ErrorList does not touch the document
440         /// contents.
441         ErrorList & errorList(std::string const & type) const;
442
443         /// The Toc backend.
444         /// This is useful only for screen visualisation of the Buffer. This
445         /// method is const because modifying this backend does not touch
446         /// the document contents.
447         TocBackend & tocBackend() const;
448
449         ///
450         Undo & undo();
451
452         /// This function is called when the buffer is changed.
453         void changed() const;
454         ///
455         void updateTocItem(std::string const &, DocIterator const &) const;
456         /// This function is called when the buffer structure is changed.
457         void structureChanged() const;
458         /// This function is called when some parsing error shows up.
459         void errors(std::string const & err, bool from_master = false) const;
460         /// This function is called when the buffer busy status change.
461         void setBusy(bool on) const;
462         /// This function is called when the buffer readonly status change.
463         void setReadOnly(bool on) const;
464         /// Update window titles of all users.
465         void updateTitles() const;
466         /// Reset autosave timers for all users.
467         void resetAutosaveTimers() const;
468         ///
469         void message(docstring const & msg) const;
470
471         ///
472         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
473         ///
474         bool hasGuiDelegate() const;
475
476         ///
477         void autoSave() const;
478         ///
479         void removeAutosaveFile() const;
480         ///
481         void moveAutosaveFile(support::FileName const & old) const;
482         ///
483         support::FileName getAutosaveFilename() const;
484
485         /// return the format of the buffer on a string
486         std::string bufferFormat() const;
487         /// return the default output format of the current backend
488         std::string getDefaultOutputFormat() const;
489
490         ///
491         bool doExport(std::string const & format, bool put_in_tempdir,
492                 std::string & result_file) const;
493         ///
494         bool doExport(std::string const & format, bool put_in_tempdir) const;
495         ///
496         bool preview(std::string const & format) const;
497         ///
498         bool isExportable(std::string const & format) const;
499         ///
500         std::vector<Format const *> exportableFormats(bool only_viewable) const;
501
502         ///
503         typedef std::vector<std::pair<InsetRef *, ParIterator> > References;
504         References & references(docstring const & label);
505         References const & references(docstring const & label) const;
506         void clearReferenceCache() const;
507         void setInsetLabel(docstring const & label, InsetLabel const * il);
508         InsetLabel const * insetLabel(docstring const & label) const;
509
510         /// return a list of all used branches (also in children)
511         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
512
513         /// sets the buffer_ member for every inset in this buffer.
514         // FIXME This really shouldn't be needed, but at the moment it's not
515         // clear how to do it just for the individual pieces we need.
516         void setBuffersForInsets() const;
517         ///
518         void updateLabels(UpdateScope = UpdateMaster) const;
519         ///
520         void updateLabels(ParIterator & parit) const;
521
522         /// Spellcheck starting from \p from.
523         /// \p from initial position, will then points to the next misspelled
524         ///    word.
525         /// \p to will points to the end of the next misspelled word.
526         /// \p word_lang will contain the found misspelled word.
527         /// \return progress if a new word was found.
528         int spellCheck(DocIterator & from, DocIterator & to,
529                 WordLangTuple & word_lang, docstring_list & suggestions) const;
530
531 private:
532         /// search for macro in local (buffer) table or in children
533         MacroData const * getBufferMacro(docstring const & name,
534                                          DocIterator const & pos) const;
535         /** Update macro table starting with position of it
536             \param it in some text inset
537         */
538         void updateMacros(DocIterator & it,
539                                      DocIterator & scope) const;
540
541         ///
542         void collectRelatives(BufferSet & bufs) const;
543
544         ///
545         bool readFileHelper(support::FileName const & s);
546         ///
547         std::vector<std::string> backends() const;
548         /** Inserts a file into a document
549             \return \c false if method fails.
550         */
551         ReadStatus readFile(Lexer &, support::FileName const & filename,
552                             bool fromString = false);
553
554         /** If we have branches that use the file suffix
555             feature, return the file name with suffix appended.
556         */
557         support::FileName exportFileName() const;
558
559         /// Use the Pimpl idiom to hide the internals.
560         class Impl;
561         /// The pointer never changes although *pimpl_'s contents may.
562         Impl * const d;
563
564         frontend::GuiBufferDelegate * gui_;
565
566         /// This function is called when the buffer structure is changed.
567         Signal structureChanged_;
568         /// This function is called when some parsing error shows up.
569         //Signal errors(std::string const &) = 0;
570         /// This function is called when some message shows up.
571         //Signal message(docstring const &) = 0;
572         /// This function is called when the buffer busy status change.
573         //Signal setBusy(bool) = 0;
574         /// Reset autosave timers for all users.
575         Signal resetAutosaveTimers_;
576 };
577
578
579 } // namespace lyx
580
581 #endif