xref: /openbsd-src/gnu/usr.bin/perl/cpan/Pod-Perldoc/lib/Pod/Perldoc/ToMan.pm (revision 48950c12d106c85f315112191a0228d7b83b9510)
1require 5.006;
2package Pod::Perldoc::ToMan;
3use strict;
4use warnings;
5use parent qw(Pod::Perldoc::BaseTo);
6
7use vars qw($VERSION);
8$VERSION = '3.17';
9
10use File::Spec::Functions qw(catfile);
11use Pod::Man 2.18;
12# This class is unlike ToText.pm et al, because we're NOT paging thru
13# the output in our particular format -- we make the output and
14# then we run nroff (or whatever) on it, and then page thru the
15# (plaintext) output of THAT!
16
17sub SUCCESS () { 1 }
18sub FAILED  () { 0 }
19
20sub is_pageable        { 1 }
21sub write_with_binmode { 0 }
22sub output_extension   { 'txt' }
23
24sub __filter_nroff  { shift->_perldoc_elem('__filter_nroff'  , @_) }
25sub __nroffer       { shift->_perldoc_elem('__nroffer'       , @_) }
26sub __bindir        { shift->_perldoc_elem('__bindir'        , @_) }
27sub __pod2man       { shift->_perldoc_elem('__pod2man'       , @_) }
28sub __output_file   { shift->_perldoc_elem('__output_file'   , @_) }
29
30sub center          { shift->_perldoc_elem('center'         , @_) }
31sub date            { shift->_perldoc_elem('date'           , @_) }
32sub fixed           { shift->_perldoc_elem('fixed'          , @_) }
33sub fixedbold       { shift->_perldoc_elem('fixedbold'      , @_) }
34sub fixeditalic     { shift->_perldoc_elem('fixeditalic'    , @_) }
35sub fixedbolditalic { shift->_perldoc_elem('fixedbolditalic', @_) }
36sub name            { shift->_perldoc_elem('name'           , @_) }
37sub quotes          { shift->_perldoc_elem('quotes'         , @_) }
38sub release         { shift->_perldoc_elem('release'        , @_) }
39sub section         { shift->_perldoc_elem('section'        , @_) }
40
41sub new {
42	my( $either ) = shift;
43	my $self = bless {}, ref($either) || $either;
44	$self->init( @_ );
45	return $self;
46	}
47
48sub init {
49	my( $self, @args ) = @_;
50
51	unless( $self->__nroffer ) {
52		my $roffer = $self->_find_roffer( $self->_roffer_candidates );
53		$self->debug( "Using $roffer\n" );
54		$self->__nroffer( $roffer );
55		}
56    else {
57	    $self->debug( "__nroffer is " . $self->__nroffer() . "\n" );
58        }
59
60	$self->_check_nroffer;
61	}
62
63sub _roffer_candidates {
64	my( $self ) = @_;
65
66	if( $self->is_openbsd ) { qw( mandoc groff nroff ) }
67	else                    { qw( groff nroff mandoc ) }
68	}
69
70sub _find_roffer {
71	my( $self, @candidates ) = @_;
72
73	my @found = ();
74	foreach my $candidate ( @candidates ) {
75		push @found, $self->_find_executable_in_path( $candidate );
76		}
77
78	return wantarray ? @found : $found[0];
79	}
80
81sub _check_nroffer {
82	return 1;
83	# where is it in the PATH?
84
85	# is it executable?
86
87	# what is its real name?
88
89	# what is its version?
90
91	# does it support the flags we need?
92
93	# is it good enough for us?
94	}
95
96sub _get_stty { `stty -a` }
97
98sub _get_columns_from_stty {
99	my $output = $_[0]->_get_stty;
100
101	if(    $output =~ /\bcolumns\s+(\d+)/ )    { return $1 }
102	elsif( $output =~ /;\s*(\d+)\s+columns;/ ) { return $1 }
103	else                                       { return  0 }
104	}
105
106sub _get_columns_from_manwidth {
107	my( $self ) = @_;
108
109	return 0 unless defined $ENV{MANWIDTH};
110
111	unless( $ENV{MANWIDTH} =~ m/\A\d+\z/ ) {
112		$self->warn( "Ignoring non-numeric MANWIDTH ($ENV{MANWIDTH})\n" );
113		return 0;
114		}
115
116	if( $ENV{MANWIDTH} == 0 ) {
117		$self->warn( "Ignoring MANWIDTH of 0. Really? Why even run the program? :)\n" );
118		return 0;
119		}
120
121	if( $ENV{MANWIDTH} =~ m/\A(\d+)\z/ ) { return $1 }
122
123	return 0;
124	}
125
126sub _get_default_width {
127	73
128	}
129
130sub _get_columns {
131	$_[0]->_get_columns_from_manwidth ||
132	$_[0]->_get_columns_from_stty     ||
133	$_[0]->_get_default_width;
134	}
135
136sub _get_podman_switches {
137	my( $self ) = @_;
138
139	my @switches = grep !m/^_/s, keys %$self;
140
141	push @switches, 'utf8' => 1;
142	$self->debug( "Pod::Man switches are [@switches]\n" );
143
144	return @switches;
145	}
146
147sub _parse_with_pod_man {
148	my( $self, $file ) = @_;
149
150	#->output_fh and ->output_string from Pod::Simple aren't
151	# working, apparently, so there's this ugly hack:
152	local *STDOUT;
153	open STDOUT, '>', $self->{_text_ref};
154	my $parser = Pod::Man->new( $self->_get_podman_switches );
155	$self->debug( "Parsing $file\n" );
156	$parser->parse_from_file( $file );
157	$self->debug( "Done parsing $file\n" );
158	close STDOUT;
159
160	$self->die( "No output from Pod::Man!\n" )
161		unless length $self->{_text_ref};
162
163	$self->_save_pod_man_output if $self->debugging;
164
165	return SUCCESS;
166	}
167
168sub _save_pod_man_output {
169	my( $self, $fh ) = @_;
170
171	$fh = do {
172		my $file = "podman.out.$$.txt";
173		$self->debug( "Writing $file with Pod::Man output\n" );
174		open my $fh2, '>', $file;
175		$fh2;
176		} unless $fh;
177
178	print { $fh } ${ $self->{_text_ref} };
179	}
180
181sub _have_groff_with_utf8 {
182	my( $self ) = @_;
183
184	return 0 unless $self->_is_groff;
185	my $roffer = $self->__nroffer;
186
187	my $minimum_groff_version = '1.20.1';
188
189	my $version_string = `$roffer -v`;
190	my( $version ) = $version_string =~ /\(?groff\)? version (\d+\.\d+(?:\.\d+)?)/;
191	$self->debug( "Found groff $version\n" );
192
193	# is a string comparison good enough?
194	if( $version lt $minimum_groff_version ) {
195		$self->warn(
196			"You have an old groff." .
197			" Update to version $minimum_groff_version for good Unicode support.\n" .
198			"If you don't upgrade, wide characters may come out oddly.\n"
199			 );
200		}
201
202	$version ge $minimum_groff_version;
203	}
204
205sub _have_mandoc_with_utf8 {
206	my( $self ) = @_;
207
208	return 0 unless $self->_is_mandoc;
209	my $roffer = $self->__nroffer;
210
211	my $minimum_mandoc_version = '1.11';
212
213	my $version_string = `$roffer -V`;
214	my( $version ) = $version_string =~ /mandoc ((\d+)\.(\d+))/;
215	$self->debug( "Found mandoc $version\n" );
216
217	# is a string comparison good enough?
218	if( $version lt $minimum_mandoc_version ) {
219		$self->warn(
220			"You have an older mandoc." .
221			" Update to version $minimum_mandoc_version for better Unicode support.\n" .
222			"If you don't upgrade, wide characters may come out oddly.\n" .
223			"Your results still might be odd. If you have groff, that's even better.\n"
224			 );
225		}
226
227	$version ge $minimum_mandoc_version;
228	}
229
230sub _collect_nroff_switches {
231	my( $self ) = shift;
232
233	my @render_switches = $self->_is_mandoc ? qw(-mandoc) : qw(-man);
234
235	push @render_switches, $self->_get_device_switches;
236
237	# Thanks to Brendan O'Dea for contributing the following block
238	if( $self->_is_roff and $self->is_linux and -t STDOUT and my ($cols) = $self->_get_columns ) {
239		my $c = $cols * 39 / 40;
240		$cols = $c > $cols - 2 ? $c : $cols -2;
241		push @render_switches, '-rLL=' . (int $c) . 'n' if $cols > 80;
242		}
243
244	# I hear persistent reports that adding a -c switch to $render
245	# solves many people's problems.  But I also hear that some mans
246	# don't have a -c switch, so that unconditionally adding it here
247	# would presumably be a Bad Thing   -- sburke@cpan.org
248    push @render_switches, '-c' if( $self->_is_roff and $self->is_cygwin );
249
250	return @render_switches;
251	}
252
253sub _get_device_switches {
254	my( $self ) = @_;
255
256	   if( $self->_is_nroff  )             { qw()              }
257	elsif( $self->_have_groff_with_utf8 )  { qw(-Kutf8 -Tutf8) }
258	elsif( $self->_is_ebcdic )             { qw(-Tcp1047)      }
259	elsif( $self->_have_mandoc_with_utf8 ) { qw(-Tutf8)        }
260	elsif( $self->_is_mandoc )             { qw()              }
261	else                                   { qw(-Tlatin1)      }
262	}
263
264sub _is_roff {
265	my( $self ) = @_;
266
267	$self->_is_nroff or $self->_is_groff;
268	}
269
270sub _is_nroff {
271	my( $self ) = @_;
272
273	$self->__nroffer =~ /\bnroff\b/;
274	}
275
276sub _is_groff {
277	my( $self ) = @_;
278
279	$self->__nroffer =~ /\bgroff\b/;
280	}
281
282sub _is_mandoc {
283	my ( $self ) = @_;
284
285	$self->__nroffer =~ /\bmandoc\b/;
286	}
287
288sub _is_ebcdic {
289	my( $self ) = @_;
290
291	return 0;
292	}
293
294sub _filter_through_nroff {
295	my( $self ) = shift;
296	$self->debug( "Filtering through " . $self->__nroffer() . "\n" );
297
298    # Maybe someone set rendering switches as part of the opt_n value
299    # Deal with that here.
300
301    my ($render, $switches) = $self->__nroffer() =~ /\A([\/a-zA-Z0-9_-]+)\b(.+)?\z/;
302
303    $self->die("no nroffer!?") unless $render;
304    my @render_switches = $self->_collect_nroff_switches;
305
306    if ( $switches ) {
307        # Eliminate whitespace
308        $switches =~ s/\s//g;
309
310        # Then seperate the switches with a zero-width positive
311        # lookahead on the dash.
312        #
313        # See:
314        # http://www.effectiveperlprogramming.com/blog/1411
315        # for a good discussion of this technique
316
317        push @render_switches, split(/(?=-)/, $switches);
318        }
319
320	$self->debug( "render is $render\n" );
321	$self->debug( "render options are @render_switches\n" );
322
323	require Symbol;
324	require IPC::Open3;
325	require IO::Handle;
326
327	my $pid = IPC::Open3::open3(
328		my $writer,
329		my $reader,
330		my $err = Symbol::gensym(),
331		$render,
332		@render_switches
333		);
334
335	$reader->autoflush(1);
336
337	use IO::Select;
338	my $selector = IO::Select->new( $reader );
339
340	$self->debug( "Writing to pipe to $render\n" );
341
342	my $offset = 0;
343	my $chunk_size = 4096;
344	my $length = length( ${ $self->{_text_ref} } );
345	my $chunks = $length / $chunk_size;
346	my $done;
347	my $buffer;
348	while( $offset <= $length ) {
349		$self->debug( "Writing chunk $chunks\n" ); $chunks++;
350		syswrite $writer, ${ $self->{_text_ref} }, $chunk_size, $offset
351			or $self->die( $! );
352		$offset += $chunk_size;
353		$self->debug( "Checking read\n" );
354		READ: {
355			last READ unless $selector->can_read( 0.01 );
356			$self->debug( "Reading\n" );
357			my $bytes = sysread $reader, $buffer, 4096;
358			$self->debug( "Read $bytes bytes\n" );
359			$done .= $buffer;
360			$self->debug( sprintf "Output is %d bytes\n",
361				length $done
362				);
363			next READ;
364			}
365		}
366	close $writer;
367	$self->debug( "Done writing\n" );
368
369	# read any leftovers
370	$done .= do { local $/; <$reader> };
371	$self->debug( sprintf "Done reading. Output is %d bytes\n",
372		length $done
373		);
374
375	if( $? ) {
376		$self->warn( "Error from pipe to $render!\n" );
377		$self->debug( 'Error: ' . do { local $/; <$err> } );
378		}
379
380
381	close $reader;
382	if( my $err = $? ) {
383		$self->debug(
384			"Nonzero exit ($?) while running `$render @render_switches`.\n" .
385			"Falling back to Pod::Perldoc::ToPod\n"
386			);
387		return $self->_fallback_to_pod( @_ );
388		}
389
390	$self->debug( "Output:\n----\n$done\n----\n" );
391
392	${ $self->{_text_ref} } = $done;
393
394	return length ${ $self->{_text_ref} } ? SUCCESS : FAILED;
395	}
396
397sub parse_from_file {
398	my( $self, $file, $outfh) = @_;
399
400	# We have a pipeline of filters each affecting the reference
401	# in $self->{_text_ref}
402	$self->{_text_ref} = \my $output;
403
404	$self->_parse_with_pod_man( $file );
405	# so far, nroff is an external command so we ensure it worked
406	my $result = $self->_filter_through_nroff;
407	return $self->_fallback_to_pod( @_ ) unless $result == SUCCESS;
408
409	$self->_post_nroff_processing;
410
411	print { $outfh } $output or
412		$self->die( "Can't print to $$self{__output_file}: $!" );
413
414	return;
415	}
416
417sub _fallback_to_pod {
418	my( $self, @args ) = @_;
419	$self->warn( "Falling back to Pod because there was a problem!\n" );
420	require Pod::Perldoc::ToPod;
421	return  Pod::Perldoc::ToPod->new->parse_from_file(@_);
422	}
423
424# maybe there's a user setting we should check?
425sub _get_tab_width { 4 }
426
427sub _expand_tabs {
428	my( $self ) = @_;
429
430	my $tab_width = ' ' x $self->_get_tab_width;
431
432	${ $self->{_text_ref} } =~ s/\t/$tab_width/g;
433	}
434
435sub _post_nroff_processing {
436	my( $self ) = @_;
437
438	if( $self->is_hpux ) {
439	    $self->debug( "On HP-UX, I'm going to expand tabs for you\n" );
440		# this used to be a pipe to `col -x` for HP-UX
441		$self->_expand_tabs;
442		}
443
444	if( $self->{'__filter_nroff'} ) {
445		$self->debug( "filter_nroff is set, so filtering\n" );
446		$self->_remove_nroff_header;
447		$self->_remove_nroff_footer;
448		}
449	else {
450		$self->debug( "filter_nroff is not set, so not filtering\n" );
451		}
452
453	$self->_handle_unicode;
454
455	return 1;
456	}
457
458# I don't think this does anything since there aren't two consecutive
459# newlines in the Pod::Man output
460sub _remove_nroff_header {
461	my( $self ) = @_;
462	$self->debug( "_remove_nroff_header is still a stub!\n" );
463	return 1;
464
465#  my @data = split /\n{2,}/, shift;
466#  shift @data while @data and $data[0] !~ /\S/; # Go to header
467#  shift @data if @data and $data[0] =~ /Contributed\s+Perl/; # Skip header
468	}
469
470# I don't think this does anything since there aren't two consecutive
471# newlines in the Pod::Man output
472sub _remove_nroff_footer {
473	my( $self ) = @_;
474	$self->debug( "_remove_nroff_footer is still a stub!\n" );
475	return 1;
476	${ $self->{_text_ref} } =~ s/\n\n+.*\w.*\Z//m;
477
478#  my @data = split /\n{2,}/, shift;
479#  pop @data if @data and $data[-1] =~ /^\w/; # Skip footer, like
480        # 28/Jan/99 perl 5.005, patch 53 1
481	}
482
483sub _unicode_already_handled {
484	my( $self ) = @_;
485
486	$self->_have_groff_with_utf8 ||
487	1  # so, we don't have a case that needs _handle_unicode
488	;
489	}
490
491sub _handle_unicode {
492# this is the job of preconv
493# we don't need this with groff 1.20 and later.
494	my( $self ) = @_;
495
496	return 1 if $self->_unicode_already_handled;
497
498	require Encode;
499
500	# it's UTF-8 here, but we need character data
501	my $text = Encode::decode( 'UTF-8', ${ $self->{_text_ref} } ) ;
502
503# http://www.mail-archive.com/groff@gnu.org/msg01378.html
504# http://linux.die.net/man/7/groff_char
505# http://www.gnu.org/software/groff/manual/html_node/Using-Symbols.html
506# http://lists.gnu.org/archive/html/groff/2011-05/msg00007.html
507# http://www.simplicidade.org/notes/archives/2009/05/fixing_the_pod.html
508# http://lists.freebsd.org/pipermail/freebsd-questions/2011-July/232239.html
509	$text =~ s/(\P{ASCII})/
510		sprintf '\\[u%04X]', ord $1
511	     /eg;
512
513	# should we encode?
514	${ $self->{_text_ref} } = $text;
515	}
516
5171;
518
519__END__
520
521=head1 NAME
522
523Pod::Perldoc::ToMan - let Perldoc render Pod as man pages
524
525=head1 SYNOPSIS
526
527  perldoc -o man Some::Modulename
528
529=head1 DESCRIPTION
530
531This is a "plug-in" class that allows Perldoc to use
532Pod::Man and C<groff> for reading Pod pages.
533
534The following options are supported:  center, date, fixed, fixedbold,
535fixeditalic, fixedbolditalic, quotes, release, section
536
537(Those options are explained in L<Pod::Man>.)
538
539For example:
540
541  perldoc -o man -w center:Pod Some::Modulename
542
543=head1 CAVEAT
544
545This module may change to use a different pod-to-nroff formatter class
546in the future, and this may change what options are supported.
547
548=head1 SEE ALSO
549
550L<Pod::Man>, L<Pod::Perldoc>, L<Pod::Perldoc::ToNroff>
551
552=head1 COPYRIGHT AND DISCLAIMERS
553
554Copyright (c) 2011 brian d foy. All rights reserved.
555
556Copyright (c) 2002,3,4 Sean M. Burke.  All rights reserved.
557
558This library is free software; you can redistribute it and/or modify it
559under the same terms as Perl itself.
560
561This program is distributed in the hope that it will be useful, but
562without any warranty; without even the implied warranty of
563merchantability or fitness for a particular purpose.
564
565=head1 AUTHOR
566
567Current maintainer: Mark Allen C<< <mallen@cpan.org> >>
568
569Past contributions from:
570brian d foy C<< <bdfoy@cpan.org> >>
571Adriano R. Ferreira C<< <ferreira@cpan.org> >>,
572Sean M. Burke C<< <sburke@cpan.org> >>
573
574=cut
575
576