xref: /openbsd-src/gnu/usr.bin/perl/cpan/Pod-Perldoc/lib/Pod/Perldoc/ToMan.pm (revision ae3cb403620ab940fbaabb3055fac045a63d56b7)
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.25';
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 || $self->is_bitrig ) { 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 = map { $_, $self->{$_} } grep !m/^_/s, keys %$self;
140
141    # There needs to be a cleaner way to handle setting
142    # the UTF-8 flag, but for now, comment out this
143    # line because it often does the wrong thing.
144    #
145    # See RT #77465
146    #
147    #push @switches, 'utf8' => 1;
148
149	$self->debug( "Pod::Man switches are [@switches]\n" );
150
151	return @switches;
152	}
153
154sub _parse_with_pod_man {
155	my( $self, $file ) = @_;
156
157	#->output_fh and ->output_string from Pod::Simple aren't
158	# working, apparently, so there's this ugly hack:
159	local *STDOUT;
160	open STDOUT, '>', $self->{_text_ref};
161	my $parser = Pod::Man->new( $self->_get_podman_switches );
162	$self->debug( "Parsing $file\n" );
163	$parser->parse_from_file( $file );
164	$self->debug( "Done parsing $file\n" );
165	close STDOUT;
166
167	$self->die( "No output from Pod::Man!\n" )
168		unless length $self->{_text_ref};
169
170	$self->_save_pod_man_output if $self->debugging;
171
172	return SUCCESS;
173	}
174
175sub _save_pod_man_output {
176	my( $self, $fh ) = @_;
177
178	$fh = do {
179		my $file = "podman.out.$$.txt";
180		$self->debug( "Writing $file with Pod::Man output\n" );
181		open my $fh2, '>', $file;
182		$fh2;
183		} unless $fh;
184
185	print { $fh } ${ $self->{_text_ref} };
186	}
187
188sub _have_groff_with_utf8 {
189	my( $self ) = @_;
190
191	return 0 unless $self->_is_groff;
192	my $roffer = $self->__nroffer;
193
194	my $minimum_groff_version = '1.20.1';
195
196	my $version_string = `$roffer -v`;
197	my( $version ) = $version_string =~ /\(?groff\)? version (\d+\.\d+(?:\.\d+)?)/;
198	$self->debug( "Found groff $version\n" );
199
200	# is a string comparison good enough?
201	if( $version lt $minimum_groff_version ) {
202		$self->warn(
203			"You have an old groff." .
204			" Update to version $minimum_groff_version for good Unicode support.\n" .
205			"If you don't upgrade, wide characters may come out oddly.\n"
206			 );
207		}
208
209	$version ge $minimum_groff_version;
210	}
211
212sub _have_mandoc_with_utf8 {
213	my( $self ) = @_;
214
215       $self->_is_mandoc and not system 'mandoc -Tlocale -V > /dev/null 2>&1';
216	}
217
218sub _collect_nroff_switches {
219	my( $self ) = shift;
220
221    my @render_switches = ('-man', $self->_get_device_switches);
222
223	# Thanks to Brendan O'Dea for contributing the following block
224	if( $self->_is_roff and -t STDOUT and my ($cols) = $self->_get_columns ) {
225		my $c = $cols * 39 / 40;
226		$cols = $c > $cols - 2 ? $c : $cols -2;
227		push @render_switches, '-rLL=' . (int $c) . 'n' if $cols > 80;
228		}
229
230	# I hear persistent reports that adding a -c switch to $render
231	# solves many people's problems.  But I also hear that some mans
232	# don't have a -c switch, so that unconditionally adding it here
233	# would presumably be a Bad Thing   -- sburke@cpan.org
234    push @render_switches, '-c' if( $self->_is_roff and $self->is_cygwin );
235
236	return @render_switches;
237	}
238
239sub _get_device_switches {
240	my( $self ) = @_;
241
242	   if( $self->_is_nroff  )             { qw()              }
243	elsif( $self->_have_groff_with_utf8 )  { qw(-Kutf8 -Tutf8) }
244	elsif( $self->_is_ebcdic )             { qw(-Tcp1047)      }
245	elsif( $self->_have_mandoc_with_utf8 ) { qw(-Tlocale)      }
246	elsif( $self->_is_mandoc )             { qw()              }
247	else                                   { qw(-Tlatin1)      }
248	}
249
250sub _is_roff {
251	my( $self ) = @_;
252
253	$self->_is_nroff or $self->_is_groff;
254	}
255
256sub _is_nroff {
257	my( $self ) = @_;
258
259	$self->__nroffer =~ /\bnroff\b/;
260	}
261
262sub _is_groff {
263	my( $self ) = @_;
264
265	$self->__nroffer =~ /\bgroff\b/;
266	}
267
268sub _is_mandoc {
269	my ( $self ) = @_;
270
271	$self->__nroffer =~ /\bmandoc\b/;
272	}
273
274sub _is_ebcdic {
275	my( $self ) = @_;
276
277	return 0;
278	}
279
280sub _filter_through_nroff {
281	my( $self ) = shift;
282	$self->debug( "Filtering through " . $self->__nroffer() . "\n" );
283
284    # Maybe someone set rendering switches as part of the opt_n value
285    # Deal with that here.
286
287    my ($render, $switches) = $self->__nroffer() =~ /\A([\/a-zA-Z0-9_\.-]+)\b(.+)?\z/;
288
289    $self->die("no nroffer!?") unless $render;
290    my @render_switches = $self->_collect_nroff_switches;
291
292    if ( $switches ) {
293        # Eliminate whitespace
294        $switches =~ s/\s//g;
295
296        # Then separate the switches with a zero-width positive
297        # lookahead on the dash.
298        #
299        # See:
300        # http://www.effectiveperlprogramming.com/blog/1411
301        # for a good discussion of this technique
302
303        push @render_switches, split(/(?=-)/, $switches);
304        }
305
306	$self->debug( "render is $render\n" );
307	$self->debug( "render options are @render_switches\n" );
308
309	require Symbol;
310	require IPC::Open3;
311	require IO::Handle;
312
313	my $pid = IPC::Open3::open3(
314		my $writer,
315		my $reader,
316		my $err = Symbol::gensym(),
317		$render,
318		@render_switches
319		);
320
321	$reader->autoflush(1);
322
323	use IO::Select;
324	my $selector = IO::Select->new( $reader );
325
326	$self->debug( "Writing to pipe to $render\n" );
327
328	my $offset = 0;
329	my $chunk_size = 4096;
330	my $length = length( ${ $self->{_text_ref} } );
331	my $chunks = $length / $chunk_size;
332	my $done;
333	my $buffer;
334	while( $offset <= $length ) {
335		$self->debug( "Writing chunk $chunks\n" ); $chunks++;
336		syswrite $writer, ${ $self->{_text_ref} }, $chunk_size, $offset
337			or $self->die( $! );
338		$offset += $chunk_size;
339		$self->debug( "Checking read\n" );
340		READ: {
341			last READ unless $selector->can_read( 0.01 );
342			$self->debug( "Reading\n" );
343			my $bytes = sysread $reader, $buffer, 4096;
344			$self->debug( "Read $bytes bytes\n" );
345			$done .= $buffer;
346			$self->debug( sprintf "Output is %d bytes\n",
347				length $done
348				);
349			next READ;
350			}
351		}
352	close $writer;
353	$self->debug( "Done writing\n" );
354
355	# read any leftovers
356	$done .= do { local $/; <$reader> };
357	$self->debug( sprintf "Done reading. Output is %d bytes\n",
358		length $done
359		);
360
361	if( $? ) {
362		$self->warn( "Error from pipe to $render!\n" );
363		$self->debug( 'Error: ' . do { local $/; <$err> } );
364		}
365
366
367	close $reader;
368	if( my $err = $? ) {
369		$self->debug(
370			"Nonzero exit ($?) while running `$render @render_switches`.\n" .
371			"Falling back to Pod::Perldoc::ToPod\n"
372			);
373		return $self->_fallback_to_pod( @_ );
374		}
375
376	$self->debug( "Output:\n----\n$done\n----\n" );
377
378	${ $self->{_text_ref} } = $done;
379
380	return length ${ $self->{_text_ref} } ? SUCCESS : FAILED;
381	}
382
383sub parse_from_file {
384	my( $self, $file, $outfh) = @_;
385
386	# We have a pipeline of filters each affecting the reference
387	# in $self->{_text_ref}
388	$self->{_text_ref} = \my $output;
389
390	$self->_parse_with_pod_man( $file );
391	# so far, nroff is an external command so we ensure it worked
392	my $result = $self->_filter_through_nroff;
393	return $self->_fallback_to_pod( @_ ) unless $result == SUCCESS;
394
395	$self->_post_nroff_processing;
396
397	print { $outfh } $output or
398		$self->die( "Can't print to $$self{__output_file}: $!" );
399
400	return;
401	}
402
403sub _fallback_to_pod {
404	my( $self, @args ) = @_;
405	$self->warn( "Falling back to Pod because there was a problem!\n" );
406	require Pod::Perldoc::ToPod;
407	return  Pod::Perldoc::ToPod->new->parse_from_file(@_);
408	}
409
410# maybe there's a user setting we should check?
411sub _get_tab_width { 4 }
412
413sub _expand_tabs {
414	my( $self ) = @_;
415
416	my $tab_width = ' ' x $self->_get_tab_width;
417
418	${ $self->{_text_ref} } =~ s/\t/$tab_width/g;
419	}
420
421sub _post_nroff_processing {
422	my( $self ) = @_;
423
424	if( $self->is_hpux ) {
425	    $self->debug( "On HP-UX, I'm going to expand tabs for you\n" );
426		# this used to be a pipe to `col -x` for HP-UX
427		$self->_expand_tabs;
428		}
429
430	if( $self->{'__filter_nroff'} ) {
431		$self->debug( "filter_nroff is set, so filtering\n" );
432		$self->_remove_nroff_header;
433		$self->_remove_nroff_footer;
434		}
435	else {
436		$self->debug( "filter_nroff is not set, so not filtering\n" );
437		}
438
439	$self->_handle_unicode;
440
441	return 1;
442	}
443
444# I don't think this does anything since there aren't two consecutive
445# newlines in the Pod::Man output
446sub _remove_nroff_header {
447	my( $self ) = @_;
448	$self->debug( "_remove_nroff_header is still a stub!\n" );
449	return 1;
450
451#  my @data = split /\n{2,}/, shift;
452#  shift @data while @data and $data[0] !~ /\S/; # Go to header
453#  shift @data if @data and $data[0] =~ /Contributed\s+Perl/; # Skip header
454	}
455
456# I don't think this does anything since there aren't two consecutive
457# newlines in the Pod::Man output
458sub _remove_nroff_footer {
459	my( $self ) = @_;
460	$self->debug( "_remove_nroff_footer is still a stub!\n" );
461	return 1;
462	${ $self->{_text_ref} } =~ s/\n\n+.*\w.*\Z//m;
463
464#  my @data = split /\n{2,}/, shift;
465#  pop @data if @data and $data[-1] =~ /^\w/; # Skip footer, like
466        # 28/Jan/99 perl 5.005, patch 53 1
467	}
468
469sub _unicode_already_handled {
470	my( $self ) = @_;
471
472	$self->_have_groff_with_utf8 ||
473	1  # so, we don't have a case that needs _handle_unicode
474	;
475	}
476
477sub _handle_unicode {
478# this is the job of preconv
479# we don't need this with groff 1.20 and later.
480	my( $self ) = @_;
481
482	return 1 if $self->_unicode_already_handled;
483
484	require Encode;
485
486	# it's UTF-8 here, but we need character data
487	my $text = Encode::decode( 'UTF-8', ${ $self->{_text_ref} } ) ;
488
489# http://www.mail-archive.com/groff@gnu.org/msg01378.html
490# http://linux.die.net/man/7/groff_char
491# http://www.gnu.org/software/groff/manual/html_node/Using-Symbols.html
492# http://lists.gnu.org/archive/html/groff/2011-05/msg00007.html
493# http://www.simplicidade.org/notes/archives/2009/05/fixing_the_pod.html
494# http://lists.freebsd.org/pipermail/freebsd-questions/2011-July/232239.html
495	$text =~ s/(\P{ASCII})/
496		sprintf '\\[u%04X]', ord $1
497	     /eg;
498
499	# should we encode?
500	${ $self->{_text_ref} } = $text;
501	}
502
5031;
504
505__END__
506
507=head1 NAME
508
509Pod::Perldoc::ToMan - let Perldoc render Pod as man pages
510
511=head1 SYNOPSIS
512
513  perldoc -o man Some::Modulename
514
515=head1 DESCRIPTION
516
517This is a "plug-in" class that allows Perldoc to use
518Pod::Man and C<groff> for reading Pod pages.
519
520The following options are supported:  center, date, fixed, fixedbold,
521fixeditalic, fixedbolditalic, quotes, release, section
522
523(Those options are explained in L<Pod::Man>.)
524
525For example:
526
527  perldoc -o man -w center:Pod Some::Modulename
528
529=head1 CAVEAT
530
531This module may change to use a different pod-to-nroff formatter class
532in the future, and this may change what options are supported.
533
534=head1 SEE ALSO
535
536L<Pod::Man>, L<Pod::Perldoc>, L<Pod::Perldoc::ToNroff>
537
538=head1 COPYRIGHT AND DISCLAIMERS
539
540Copyright (c) 2011 brian d foy. All rights reserved.
541
542Copyright (c) 2002,3,4 Sean M. Burke.  All rights reserved.
543
544This library is free software; you can redistribute it and/or modify it
545under the same terms as Perl itself.
546
547This program is distributed in the hope that it will be useful, but
548without any warranty; without even the implied warranty of
549merchantability or fitness for a particular purpose.
550
551=head1 AUTHOR
552
553Current maintainer: Mark Allen C<< <mallen@cpan.org> >>
554
555Past contributions from:
556brian d foy C<< <bdfoy@cpan.org> >>
557Adriano R. Ferreira C<< <ferreira@cpan.org> >>,
558Sean M. Burke C<< <sburke@cpan.org> >>
559
560=cut
561
562