2 # bibtex_to_paper opens the paper corresponding to a bibtex key
3 # and is released under the terms of the GNU GPL version 3, or any
4 # later version, at your option. See the file README and COPYING for
6 # Copyright 2014 by Don Armstrong <don@donarmstrong.com>.
19 use MLDBM qw(DB_FILE Storable);
20 use Fcntl qw/O_RDWR O_CREAT O_TRUNC/;
24 bibtex_to_paper - opens the paper corresponding to a bibtex key
28 bibtex_to_paper [options] bibtexkey
31 --bibtex, -b bibtex file to look up key in
32 --bibtex-cache, -c bibtex cache file
33 --build-cache, -B build cache using bibtex files
34 --pdf-dir pdf directory
35 --pdfviewer, -p pdf viewer to use
36 --debug, -d debugging level (Default 0)
37 --help, -h display this help
38 --man, -m display manual
46 Bibtex file to look key up in
48 =item B<--bibtex-cache, -c>
50 Bibtex cache file; rebuilt if bibtex file changes
52 =item B<--pdfviewer, -p>
54 PDF viewer to use; defaults to evince unless a .xoj exists, in which
59 Debug verbosity. (Default 0)
63 Display brief usage information.
80 my %options = (debug => 0,
86 'build_cache|build-cache|B!',
88 'bibtex_cache|bibtex-cache|c=s',
90 'debug|d+','help|h|?','man|m');
92 pod2usage() if $options{help};
93 pod2usage({verbose=>2}) if $options{man};
95 $DEBUG = $options{debug};
98 if (not exists $options{bibtex} and
99 not exists $options{bibtex_cache}) {
101 "You must give at least one of --bibtex".
105 pod2usage(join("\n",@USAGE_ERRORS)) if @USAGE_ERRORS;
107 sub parse_bibtex_file {
108 my ($file,$entries) = @_;
110 my $bibfile = Text::BibTex::File->new($file)
111 or die "Unable to open $bibfile for reading: $!";
114 while ($entry = Text::BibTex::Entry->new($bibfile)) {
115 if ($entry->metatype() eq 'BTE_COMMENT') {
116 push @entry_comments,$entry->value();
117 } elsif ($entry->metatype() eq 'BTE_REGULAR') {
118 my $entry_key = $entry->key();
120 if (defined $entry_key) {
121 # if there is a file comment, use it as the file name
122 for my $comment (@entry_comments) {
123 next unless $comment =~ /^\s*file(?:name)?:?\s*(.+?)\s*$/i;
127 # if there is a file key, use that as the file name
128 # if there is a doi, then use that
129 # if there is a html, then use that
130 if (not defined $link_name) {
131 my @possible_fields = $entry->get(qw(file doi html));
132 for my $possible_field (@possible_fields) {
133 if (defined $possible_field and length $possible_field) {
134 $link_name = $possible_field;
140 if (not exists $entries->{$entry_key} or
143 $entries->{$entry_key} = $link_name
145 # reset the entry comments
146 @entry_comments = ();
154 sub initialize_database {
156 return open_cache($cache,1);
160 my ($cache,$initialize) @_;
161 my $open_flags = O_RDWR|O_CREAT;
163 $open_flags = $open_flags | O_TRUNC;
167 tie %entries, MLDBM => $cache
169 or die "Unable to create create/truncate $cache: $!";