./0000755000000000000000000000000013543566660007727 5ustar rootroot./.gitignore0000644000000000000000000000003313543566660011713 0ustar rootrootbuild/ dist/ *.bak ddgr.py ./ddgr.10000644000000000000000000002161513543566660010736 0ustar rootroot.TH "DDGR" "1" "3 Sep 2019" "Version 1.7" "User Commands" .SH NAME ddgr \- DuckDuckGo from the terminal .SH SYNOPSIS .B ddgr [OPTIONS] [KEYWORD [KEYWORD ...]] .SH DESCRIPTION .B ddgr is a command-line tool to search DuckDuckGo. \fBddgr\fR shows the title, URL and text context for each result. Results are fetched in pages. Keyboard shortcuts are available for page navigation. Results are indexed and a result URL can be opened in a browser using the index number. There is no configuration file as aliases serve the same purpose for this utility. Supports sequential searches in a single instance. .PP .B Features .PP * Fast and clean; custom color * Designed for maximum readability at minimum space * Instant answers (supported by DDG html version) * Custom number of results per page * Navigation, browser integration * Search and option completion scripts (Bash, Fish, Zsh) * DuckDuckGo Bangs (along with completion) * Open the first result in browser (I'm Feeling Ducky) * REPL for continuous searches * Keywords (e.g. `filetype:mime`, `site:somesite.com`) * Limit search by time, specify region, disable safe search * HTTPS proxy support, optionally disable User Agent * Do Not Track set by default * Supports custom url handler script or cmdline utility * Thoroughly documented, man page with examples * Minimal dependencies .SH OPTIONS .TP .BI "-h, --help" Show help text and exit. .TP .BI "-n, --num=" N Show N results per page (default 10). N must be between 0 and 25. N=0 disables fixed paging and shows actual number of results fetched per page. .TP .BI "-r, --reg=" REG Region-specific search e.g. 'us-en' for US (default); visit https://duckduckgo.com/params. .TP .BI "-C, --nocolor" Disable color output. .TP .BI "--colors=" COLORS Set output colors. Refer to the \fBCOLORS\fR section below for details. .TP .BI "-j, --ducky" Open the first result in a web browser; implies \fB--noprompt\fR. Feeling Ducky? .TP .BI "-t, --time=" SPAN Time limit search [d=past day, w=past week, m=past month] (default=any time). .TP .BI "-w, --site=" SITE Search a site using DuckDuckGo. .TP .BI "-x, --expand" Expand URLs instead of showing only the domain name (default). .TP .BI "-p, --proxy=" URI Tunnel traffic through an HTTP proxy. \fIURI\fR is of the form \fI[http[s]://][user:pwd@]host[:port]\fR. The proxy server must support HTTP CONNECT tunneling and must not block port 443 for the relevant DuckDuckGo hosts. If a proxy is not explicitly given, the \fIhttps_proxy\fR or \fIHTTPS_PROXY\fR environment variable (if available) is used instead. .TP .BI "--unsafe" Disable safe search. .TP .BI "--noua" Disable user agent. Results are fetched faster. .TP .BI "--json" Output in JSON format; implies \fB--noprompt\fR. .TP .BI "--gb, --gui-browser" Open a bang directly in a GUI browser. .TP .BI "--np, --noprompt" Perform search and exit; do not prompt for further interactions. .TP .BI "--url-handler=" UTIL Custom script or command-line utility to open urls with. .TP .BI "--show-browser-logs" Do not suppress browser output when opening result in browser; that is, connect stdout and stderr of the browser to ddgr's stdout and stderr instead of /dev/null. By default, browser output is suppressed (due to certain graphical browsers spewing messages to console) unless the \fBBROWSER\fR environment variable is a known text-based browser: elinks, links, lynx, w3m or www-browser. .TP .BI "-v, --version" Show version number and exit. .TP .BI "-d, --debug" Enable debugging. .SH OMNIPROMPT KEYS .TP .BI "n, p, f" Fetch the next, previous or first set of search results. .TP .BI "index" Open the result corresponding to index in browser. .TP .BI o " [index|range|a ...]" Open space-separated result indices, numeric ranges or all indices, if 'a' is specified, in the browser. .TP .BI O " [index|range|a ...]" Works similar to key 'o', but tries to ignore text-based browsers (even if BROWSER is set) and open links in a GUI browser. .TP .BI d " keywords" Initiate a new DuckDuckGo search for \fIkeywords\fR with original options. This key should be used to search omniprompt keys (including itself) and indices. .TP .BI "x" Toggle url expansion. .TP .BI "c index" Copy url to clipboard. .TP .BI "q, ^D, double Enter" Exit ddgr. .TP .BI "?" Show omniprompt help. .TP .BI * Any other string initiates a new search with original options. .SH COLORS \fBddgr\fR allows you to customize the color scheme via a six-letter string, reminiscent of BSD \fBLSCOLORS\fR. The six letters represent the colors of .IP - 2 indices .PD 0 \" Change paragraph spacing to 0 in the list .IP - 2 titles .IP - 2 URLs .IP - 2 metadata/publishing info .IP - 2 abstracts .IP - 2 prompts .PD 1 \" Restore paragraph spacing .TP respectively. The six-letter string is passed in either as the argument to the \fB--colors\fR option, or as the value of the environment variable \fBDDGR_COLORS\fR. .TP We offer the following colors/styles: .TS tab(;) box; l|l -|- l|l. Letter;Color/Style a;black b;red c;green d;yellow e;blue f;magenta g;cyan h;white i;bright black j;bright red k;bright green l;bright yellow m;bright blue n;bright magenta o;bright cyan p;bright white A-H;bold version of the lowercase-letter color I-P;bold version of the lowercase-letter bright color x;normal X;bold y;reverse video Y;bold reverse video .TE .TP .TP The default colors string is \fIoCdgxy\fR, which stands for .IP - 2 bright cyan indices .PD 0 \" Change paragraph spacing to 0 in the list .IP - 2 bold green titles .IP - 2 yellow URLs .IP - 2 cyan metadata/publishing info .IP - 2 normal abstracts .IP - 2 reverse video prompts .PD 1 \" Restore paragraph spacing .TP Note that .IP - 2 Bright colors (implemented as \\x1b[90m - \\x1b[97m) may not be available in all color-capable terminal emulators; .IP - 2 Some terminal emulators draw bold text in bright colors instead; .IP - 2 Some terminal emulators only distinguish between bold and bright colors via a default-off switch. .TP Please consult the manual of your terminal emulator as well as \fIhttps://en.wikipedia.org/wiki/ANSI_escape_code\fR for details. .SH ENVIRONMENT .TP .BI BROWSER Overrides the default browser. Ref: .I http://docs.python.org/library/webbrowser.html .TP .BI DDGR_COLORS Refer to the \fBCOLORS\fR section. .TP .BI DISABLE_PROMPT_COLOR Force a plain omniprompt if you are facing issues with colors at the prompt. .TP .BI "HTTPS_PROXY, https_proxy" Refer to the \fB--proxy\fR option. .SH EXAMPLES .PP .IP 1. 4 DuckDuckGo \fBhello world\fR: .PP .EX .IP .B ddgr hello world .EE .PP .IP 2. 4 \fBI'm Feeling Ducky\fR search: .PP .EX .IP .B ddgr -j lucky ducks .EE .PP .IP 3. 4 \fBDuckDuckGo Bang\fR search 'hello world' in Wikipedia: .PP .EX .IP .B ddgr !w hello world .B ddgr \\\\!w hello world // bash-specific, need to escape ! on bash .EE .PP .IP "" 4 Bangs work at the omniprompt too. To look up bangs, visit https://duckduckgo.com/bang?#bangs-list. .PP .IP 4. 4 \fBBang alias\fR to fire from the cmdline, open results in a GUI browser and exit: .PP .EX .IP .B alias bang='ddgr --gb --np' .IP .B bang !w hello world .B bang \\\\!w hello world // bash-specific, need to escape ! on bash .EE .PP .IP 5. 4 \fBWebsite specific\fR search: .PP .EX .IP .B ddgr -w amazon.com digital camera .EE .PP .IP "" 4 Site specific search continues at omniprompt. .EE .PP .IP 6. 4 Search for a \fBspecific file type\fR: .PP .EX .IP .B ddgr instrumental filetype:mp3 .EE .PP .IP 7. 4 Fetch results on IPL cricket from \fBIndia\fR in \fBEnglish\fR: .PP .EX .IP .B ddgr -r in-en IPL cricket .EE .PP .IP "" 4 To find your region parameter token visit https://duckduckgo.com/params. .PP .IP 8. 4 Search \fBquoted text\fR: .PP .EX .IP .B ddgr it\(rs's a \(rs\(dqbeautiful world\(rs\(dq in spring .EE .PP .IP 9. 4 Show \fBcomplete urls\fR in search results (instead of only domain name): .PP .EX .IP .B ddgr -x ddgr .EE .PP .IP 10. 4 Use a \fBcustom color scheme\fR, e.g., one warm color scheme designed for Solarized Dark: .PP .EX .IP .B ddgr --colors bjdxxy hello world .IP .B DDGR_COLORS=bjdxxy ddgr hello world .EE .PP .IP 11. 4 Tunnel traffic through an \fBHTTPS proxy\fR, e.g., a local Privoxy instance listening on port 8118: .PP .EX .IP .B ddgr --proxy localhost:8118 hello world .EE .PP .IP "" 4 By default the environment variable \fIhttps_proxy\fR (or \fIHTTPS_PROXY\fR) is used, if defined. .EE .PP .IP 12. 4 Look up \fBn\fR, \fBp\fR, \fBo\fR, \fBO\fR, \fBq\fR, \fBd keywords\fR or a result index at the \fBomniprompt\fR: as the omniprompt recognizes these keys or index strings as commands, you need to prefix them with \fBd\fR, e.g., .PP .EX .PD 0 .IP .B d n .IP .B d d keywords .IP .B d 1 .PD .EE .SH AUTHOR Arun Prakash Jana .SH HOME .I https://github.com/jarun/ddgr .SH REPORTING BUGS .I https://github.com/jarun/ddgr/issues .SH LICENSE Copyright \(co 2016-2019 Arun Prakash Jana .PP License GPLv3+: GNU GPL version 3 or later . .br This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. ./.github/0000755000000000000000000000000013543566660011267 5ustar rootroot./.github/FUNDING.yml0000644000000000000000000000013313543566660013101 0ustar rootrootcustom: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=RMLTQ76JSXJ4Q ./CHANGELOG0000644000000000000000000000366313543566660011151 0ustar rootrootddgr v1.7 2018-09-03 What's in? - Use setproctitle to set process name - Monkeypatch textwrap for CJK wide characters - Fix write to GNU Screen paste buffer - Refresh current page on URL expansion toggle - Smarter colorization and better support for native terminals on Windows - Handle bangs in the form g! ------------------------------------------------------------------------------- ddgr v1.6 2018-11-16 What's in? - User interface revamped - DDG instant answers - Haiku OS clipboard support - Packaging preparation for PyPI ------------------------------------------------------------------------------- ddgr v1.5 2018-09-10 What's in? - Support xclip as a clipboard utility on *nix - Support GNU Screen and tmux as clipboard fallback - Support Termux clipboard on Android ------------------------------------------------------------------------------- ddgr v1.4 2018-04-05 What's in? - Copy URL at omniprompt - Check default stdout encoding at start - New environment variable DISABLE_PROMPT_COLOR ------------------------------------------------------------------------------- ddgr v1.2 2017-12-08 What's in? - Remove Pyhton3 'requests' library dependency - Remove Python 3.3 (EOL) support - Fix zsh completion script issue ------------------------------------------------------------------------------- ddgr v1.1 2017-11-29 What's in? - Option `--num` to specify the number of results to show per page - Omniprompt key `x` to toggle URL expansion on-the-fly. - Option `-t` to limit search by time - Option `--gui-browser` to open bangs directly in GUI browser - Retrieve next index parameters from fetched data - Custom user agent for ddgr ------------------------------------------------------------------------------- ddgr v1.0 2017-11-05 What's in? - This is the first release of `ddgr`. For a list of features visit: https://github.com/jarun/ddgr#features ------------------------------------------------------------------------------- ./LICENSE0000644000000000000000000010451313543566660010740 0ustar rootroot GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ./.circleci/0000755000000000000000000000000013543566660011562 5ustar rootroot./.circleci/config.yml0000644000000000000000000000333513543566660013556 0ustar rootrootversion: 2 test-template: &test-template working_directory: ~/ddgr environment: CI_FORCE_TEST: 1 steps: - run: command: | apt update && apt install -y --no-install-recommends git make pip install --upgrade setuptools flake8 pylint - checkout - run: command: | python3 -m flake8 ddgr echo ddgr | xargs pylint make test jobs: py35: docker: - image: python:3.5-slim <<: *test-template py36: docker: - image: python:3.6-slim <<: *test-template py37: docker: - image: python:3.7-slim <<: *test-template package-and-publish: machine: true working_directory: ~/ddgr steps: - checkout - run: name: "package with packagecore" command: | # Use latest installed python3 from pyenv export PYENV_VERSION="$(pyenv versions | grep -Po '\b3\.\d+\.\d+' | tail -1)" pip install packagecore packagecore -o ./dist/ ${CIRCLE_TAG#v} - run: name: "publish to GitHub" command: | go get github.com/tcnksm/ghr ghr -t ${GITHUB_API_TOKEN} -u ${CIRCLE_PROJECT_USERNAME} -r ${CIRCLE_PROJECT_REPONAME} -c ${CIRCLE_SHA1} -replace ${CIRCLE_TAG} ./dist/ workflows: version: 2 test: jobs: &all-tests - py35 - py36 - py37 nightly: triggers: - schedule: cron: "0 0 * * 6" filters: branches: only: - master jobs: *all-tests publish-github-release: jobs: - package-and-publish: filters: tags: only: /^v.*/ branches: ignore: /.*/ ./pyproject.toml0000644000000000000000000000006213543566660012641 0ustar rootroot[build-system] requires = ["setuptools", "wheel"] ./packagecore.yaml0000644000000000000000000000256113543566660013063 0ustar rootrootname: ddgr maintainer: Arun Prakash Jana license: GPLv3 summary: DuckDuckGo from the terminal. homepage: https://github.com/jarun/ddgr commands: install: - make PREFIX="/usr" install DESTDIR="${BP_DESTDIR}" packages: archlinux: builddeps: - make deps: - python container: "archlinux/base" centos7.4: builddeps: - make deps: - python commands: pre: - yum install epel-release centos7.5: builddeps: - make deps: - python commands: pre: - yum install epel-release centos7.6: builddeps: - make deps: - python commands: pre: - yum install epel-release debian9: builddeps: - make deps: - python3 debian10: builddeps: - make deps: - python3 fedora26: builddeps: - make deps: - python3 fedora27: builddeps: - make deps: - python3 fedora28: builddeps: - make deps: - python3 fedora29: builddeps: - make deps: - python3 fedora30: builddeps: - make deps: - python3 opensuse42.3: builddeps: - make deps: - python3 ubuntu16.04: builddeps: - make deps: - python3 ubuntu18.04: builddeps: - make deps: - python3 ./README.md0000644000000000000000000003504113543566660011211 0ustar rootroot

ddgr

Latest release AUR Homebrew PyPI Debian Buster+ Fedora 26+ openSUSE Leap 15.0+ Ubuntu Bionic+

Availability License Build Status

Asciicast

`ddgr` is a cmdline utility to search DuckDuckGo from the terminal. While [googler](https://github.com/jarun/googler) is extremely popular among cmdline users, in many forums the need of a similar utility for privacy-aware DuckDuckGo came up. [DuckDuckGo Bangs](https://duckduckgo.com/bang) are super-cool too! So here's `ddgr` for you! Unlike the web interface, you can specify the number of search results you would like to see per page. It's more convenient than skimming through 30-odd search results per page. The default interface is carefully designed to use minimum space without sacrificing readability. A big advantage of `ddgr` over `googler` is DuckDuckGo works over the Tor network. `ddgr` isn't affiliated to DuckDuckGo in any way. *Love smart and efficient utilities? Explore [my repositories](https://github.com/jarun?tab=repositories). Buy me a cup of coffee if they help you.*

Donate via PayPal!

### Table of contents - [Features](#features) - [Installation](#installation) - [Dependencies](#dependencies) - [From a package manager](#from-a-package-manager) - [Release packages](#release-packages) - [From source](#from-source) - [Running standalone](#running-standalone) - [Shell completion](#shell-completion) - [Usage](#usage) - [Cmdline options](#cmdline-options) - [Configuration file](#configuration-file) - [Text-based browser integration](#text-based-browser-integration) - [Colors](#colors) - [Examples](#examples) - [Troubleshooting](#troubleshooting) - [Collaborators](#collaborators) - [In the Press](#in-the-press) ### Features - Fast and clean; custom color - Designed for maximum readability at minimum space - Instant answers (supported by DDG html version) - Custom number of results per page - Navigation, browser integration - Search and option completion scripts (Bash, Fish, Zsh) - DuckDuckGo Bangs (along with completion) - Open the first result in browser (I'm Feeling Ducky) - REPL for continuous searches - Keywords (e.g. `filetype:mime`, `site:somesite.com`) - Limit search by time, specify region, disable safe search - HTTPS proxy support, optionally disable User Agent - Do Not Track set by default - Supports custom url handler script or cmdline utility - Thoroughly documented, man page with examples - Minimal dependencies ### Installation #### Dependencies `ddgr` requires Python 3.5 or later. Only the latest patch release of each minor version is supported. To copy url to clipboard at the omniprompt, `ddgr` looks for `xsel` or `xclip` or `termux-clipboard-set` (in the same order) on Linux, `pbcopy` (default installed) on OS X, `clip` (default installed) on Windows and `clipboard` (default installed) on Haiku. It also supports GNU Screen and tmux copy-paste buffers in the absence of X11. Note: v1.1 and below require the Python3 `requests` library to make HTTPS requests. This dependency is removed in the later releases. #### From a package manager - [AUR](https://aur.archlinux.org/packages/ddgr/) (`yay -S ddgr`) - [CRUX](https://crux.nu/portdb/?a=search&q=ddgr) (`prt-get depinst ddgr`) - [Debian](https://packages.debian.org/search?keywords=ddgr&searchon=names&exact=1) (`apt-get install ddgr`) - [Fedora](https://apps.fedoraproject.org/packages/ddgr) (`dnf install ddgr`) - [FreeBSD](https://www.freshports.org/www/ddgr/) (`pkg install ddgr`) - [Haiku](https://github.com/haikuports/haikuports/tree/master/www-client/ddgr) (`pkgman install ddgr`) - [macOS/Homebrew](http://formulae.brew.sh/formula/ddgr) (`brew install ddgr`) - [NixOS](https://github.com/NixOS/nixpkgs/tree/master/pkgs/applications/misc/ddgr) (`nix-env -i ddgr`) - [openSUSE](https://software.opensuse.org/package/ddgr) (`zypper in ddgr`) - [PyPI](https://pypi.org/project/ddgr/) (`pip3 install ddgr`) - [Raspbian Testing](https://archive.raspbian.org/raspbian/pool/main/d/ddgr/) (`apt-get install ddgr`) - [Slackware](http://slackbuilds.org/repository/14.2/network/ddgr/) (`slackpkg install ddgr`) - [Snap Store](https://snapcraft.io/ddgr/) (`snap install ddgr`) - [Solus](https://packages.getsol.us/shannon/d/ddgr/) (`eopkg install ddgr`) - [Source Mage](http://codex.sourcemage.org/test/utils/ddgr/) (`cast ddgr`) - [Termux](https://pypi.org/project/ddgr/) (`pip3 install ddgr`) - [Ubuntu](https://packages.ubuntu.com/search?keywords=ddgr&searchon=names&exact=1) (`apt-get install ddgr`) - [Void Linux](https://github.com/void-linux/void-packages/tree/master/srcpkgs/ddgr) (`xbps-install -S ddgr`) #### Release packages Packages for Arch Linux, CentOS, Debian, Fedora, OpenSUSE Leap, Solus, and Ubuntu are available with the [latest stable release](https://github.com/jarun/ddgr/releases/latest). #### From source If you have git installed, clone this repository. Otherwise download the [latest stable release](https://github.com/jarun/ddgr/releases/latest) or [development version](https://github.com/jarun/ddgr/archive/master.zip). To install to the default location (`/usr/local`): $ sudo make install To remove `ddgr` and associated docs, run $ sudo make uninstall `PREFIX` is supported, in case you want to install to a different location. #### Running standalone `ddgr` is a standalone executable (and can run even on environments like Termux). From the containing directory: $ ./ddgr #### Shell completion Search keyword and option completion scripts for Bash, Fish and Zsh can be found in respective subdirectories of [`auto-completion/`](auto-completion). Please refer to your shell's manual for installation instructions. ### Usage #### Cmdline options ``` usage: ddgr [-h] [-n N] [-r REG] [--colorize [{auto,always,never}]] [-C] [--colors COLORS] [-j] [-t SPAN] [-w SITE] [-x] [-p URI] [--unsafe] [--noua] [--json] [--gb] [--np] [--url-handler UTIL] [--show-browser-logs] [-v] [-d] [KEYWORD [KEYWORD ...]] DuckDuckGo from the terminal. positional arguments: KEYWORD search keywords optional arguments: -h, --help show this help message and exit -n N, --num N show N (0<=N<=25) results per page (default 10); N=0 shows actual number of results fetched per page -r REG, --reg REG region-specific search e.g. 'us-en' for US (default); visit https://duckduckgo.com/params --colorize [{auto,always,never}] whether to colorize output; defaults to 'auto', which enables color when stdout is a tty device; using --colorize without an argument is equivalent to --colorize=always -C, --nocolor equivalent to --colorize=never --colors COLORS set output colors (see man page for details) -j, --ducky open the first result in a web browser; implies --np -t SPAN, --time SPAN time limit search [d (1 day), w (1 wk), m (1 month)] -w SITE, --site SITE search sites using DuckDuckGo -x, --expand Show complete url in search results -p URI, --proxy URI tunnel traffic through an HTTPS proxy; URI format: [http[s]://][user:pwd@]host[:port] --unsafe disable safe search --noua disable user agent --json output in JSON format; implies --np --gb, --gui-browser open a bang directly in gui browser --np, --noprompt perform search and exit, do not prompt --url-handler UTIL custom script or cli utility to open results --show-browser-logs do not suppress browser output (stdout and stderr) -v, --version show program's version number and exit -d, --debug enable debugging omniprompt keys: n, p, f fetch the next, prev or first set of search results index open the result corresponding to index in browser o [index|range|a ...] open space-separated result indices, ranges or all O [index|range|a ...] like key 'o', but try to open in a GUI browser d keywords new DDG search for 'keywords' with original options should be used to search omniprompt keys and indices x toggle url expansion c index copy url to clipboard q, ^D, double Enter exit ddgr ? show omniprompt help * other inputs are considered as new search keywords ``` #### Configuration file `ddgr` doesn't have any! Use aliases, environment variables and auto-completion scripts. #### Text-based browser integration `ddgr` works out of the box with several text-based browsers if the `BROWSER` environment variable is set. For instance, $ export BROWSER=w3m or for one-time use, $ BROWSER=w3m ddgr query Due to certain graphical browsers spewing messages to the console, `ddgr` suppresses browser output by default unless `BROWSER` is set to one of the known text-based browsers: currently `elinks`, `links`, `lynx`, `w3m` or `www-browser`. If you use a different text-based browser, you will need to explicitly enable browser output with the `--show-browser-logs` option. If you believe your browser is popular enough, please submit an issue or pull request and we will consider whitelisting it. See the man page for more details on `--show-browser-logs`. If you need to use a GUI browser with `BROWSER` set, use the omniprompt key `O`. `ddgr` will try to ignore text-based browsers and invoke a GUI browser. Browser logs are always suppressed with `O`. #### Colors The color configuration is similar to that of [`googler` colors](https://github.com/jarun/googler#colors). The default color string is `oCdgxy`. `ddgr` recognizes the environment variable `DDGR_COLORS`. Details are available in the `ddgr` man page. ### Examples 1. DuckDuckGo **hello world**: $ ddgr hello world 2. **I'm Feeling Ducky** search: $ ddgr -j lucky ducks 3. **DuckDuckGo Bang** search `hello world` in Wikipedia: $ ddgr !w hello world $ ddgr \!w hello world // bash-specific, need to escape ! on bash Bangs work at the omniprompt too. To look up bangs, visit https://duck‐duckgo.com/bang?#bangs-list. 4. **Bang alias** to fire from the cmdline, open results in a GUI browser and exit: alias bang='ddgr --gb --np' $ bang !w hello world $ bang \!w hello world // bash-specific, need to escape ! on bash 5. **Website specific** search: $ ddgr -w amazon.com digital camera Site specific search continues at omniprompt. 6. Search for a **specific file type**: $ ddgr instrumental filetype:mp3 7. Fetch results on IPL cricket from **India** in **English**: $ ddgr -r in-en IPL cricket To find your region parameter token visit https://duckduckgo.com/params. 8. Search **quoted text**: $ ddgr it\'s a \"beautiful world\" in spring 9. Show **complete urls** in search results (instead of only domain name): $ ddgr -x ddgr 10. Use a **custom color scheme**, e.g., one warm color scheme designed for Solarized Dark: $ ddgr --colors bjdxxy hello world $ DDGR_COLORS=bjdxxy ddgr hello world 11. Tunnel traffic through an **HTTPS proxy**, e.g., a local Privoxy instance listening on port 8118: $ ddgr --proxy localhost:8118 hello world By default the environment variable `https_proxy` (or `HTTPS_PROXY`) is used, if defined. 12. Look up `n`, `p`, `o`, `O`, `q`, `d keywords` or a result index at the **omniprompt**: as the omniprompt recognizes these keys or index strings as commands, you need to prefix them with `d`, e.g., d n d g keywords d 1 ### Troubleshooting 1. Some users have reported problems with a colored omniprompt (refer to issue [#40](https://github.com/jarun/ddgr/issues/40)) with iTerm2 on OS X. To force a plain omniprompt: export DISABLE_PROMPT_COLOR=1 ### Collaborators - [Arun Prakash Jana](https://github.com/jarun) - [Johnathan Jenkins](https://github.com/shaggytwodope) - [SZ Lin](https://github.com/szlin) - [Alex Gontar](https://github.com/mosegontar) Copyright © 2016-2019 [Arun Prakash Jana](mailto:engineerarun@gmail.com) ### In the Press - [Fossbytes](https://fossbytes.com/search-duckduckgo-from-terminal-ddgr/) - [Hacker News](https://news.ycombinator.com/item?id=19606101) - [Information Security Squad](http://itsecforu.ru/2017/11/21/%D0%BA%D0%B0%D0%BA-%D0%B8%D1%81%D0%BA%D0%B0%D1%82%D1%8C-%D0%B2-duckduckgo-%D0%B8%D0%B7-%D0%BA%D0%BE%D0%BC%D0%B0%D0%BD%D0%B4%D0%BD%D0%BE%D0%B9-%D1%81%D1%82%D1%80%D0%BE%D0%BA%D0%B8-linux/) - [LinOxide](https://linoxide.com/tools/search-duckduckgo-command-line/) - [OMG! Ubuntu!](http://www.omgubuntu.co.uk/2017/11/duck-duck-go-terminal-app) - [Tecmint](https://www.tecmint.com/search-duckduckgo-from-linux-terminal/) ./ddgr0000755000000000000000000020735213543566660010606 0ustar rootroot#!/usr/bin/env python3 # Copyright (C) 2016-2019 Arun Prakash Jana # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import argparse import codecs import collections import functools import gzip import html.entities import html.parser import json import locale import logging import os import platform import shutil import signal from subprocess import Popen, PIPE, DEVNULL import sys import tempfile import textwrap import unicodedata import urllib.error import urllib.parse import urllib.request import webbrowser try: import readline except ImportError: pass try: import setproctitle setproctitle.setproctitle('ddgr') except (ImportError, Exception): pass # Basic setup logging.basicConfig(format='[%(levelname)s] %(message)s') LOGGER = logging.getLogger() LOGDBG = LOGGER.debug LOGERR = LOGGER.error def sigint_handler(signum, frame): print('\nInterrupted.', file=sys.stderr) sys.exit(1) try: signal.signal(signal.SIGINT, sigint_handler) except ValueError: # signal only works in main thread pass # Constants _VERSION_ = '1.7' COLORMAP = {k: '\x1b[%sm' % v for k, v in { 'a': '30', 'b': '31', 'c': '32', 'd': '33', 'e': '34', 'f': '35', 'g': '36', 'h': '37', 'i': '90', 'j': '91', 'k': '92', 'l': '93', 'm': '94', 'n': '95', 'o': '96', 'p': '97', 'A': '30;1', 'B': '31;1', 'C': '32;1', 'D': '33;1', 'E': '34;1', 'F': '35;1', 'G': '36;1', 'H': '37;1', 'I': '90;1', 'J': '91;1', 'K': '92;1', 'L': '93;1', 'M': '94;1', 'N': '95;1', 'O': '96;1', 'P': '97;1', 'x': '0', 'X': '1', 'y': '7', 'Y': '7;1', }.items()} USER_AGENT = 'ddgr/{} (textmode; Linux x86_64; 1024x768)'.format(_VERSION_) TEXT_BROWSERS = ['elinks', 'links', 'lynx', 'w3m', 'www-browser'] INDENT = 5 # Global helper functions def open_url(url): """Open an URL in the user's default web browser. The string attribute ``open_url.url_handler`` can be used to open URLs in a custom CLI script or utility. A subprocess is spawned with url as the parameter in this case instead of the usual webbrowser.open() call. Whether the browser's output (both stdout and stderr) are suppressed depends on the boolean attribute ``open_url.suppress_browser_output``. If the attribute is not set upon a call, set it to a default value, which means False if BROWSER is set to a known text-based browser -- elinks, links, lynx, w3m or 'www-browser'; or True otherwise. The string attribute ``open_url.override_text_browser`` can be used to ignore env var BROWSER as well as some known text-based browsers and attempt to open url in a GUI browser available. Note: If a GUI browser is indeed found, this option ignores the program option `show-browser-logs` """ LOGDBG('Opening %s', url) # Custom URL handler gets max priority if hasattr(open_url, 'url_handler'): pipe = Popen([open_url.url_handler, url], stdin=PIPE) pipe.communicate() return browser = webbrowser.get() if open_url.override_text_browser: browser_output = open_url.suppress_browser_output for name in [b for b in webbrowser._tryorder if b not in TEXT_BROWSERS]: browser = webbrowser.get(name) LOGDBG(browser) # Found a GUI browser, suppress browser output open_url.suppress_browser_output = True break if open_url.suppress_browser_output: _stderr = os.dup(2) os.close(2) _stdout = os.dup(1) os.close(1) fd = os.open(os.devnull, os.O_RDWR) os.dup2(fd, 2) os.dup2(fd, 1) try: browser.open(url, new=2) finally: if open_url.suppress_browser_output: os.close(fd) os.dup2(_stderr, 2) os.dup2(_stdout, 1) if open_url.override_text_browser: open_url.suppress_browser_output = browser_output def https_get(url, headers=None, proxies=None, expected_code=None): """Sends an HTTPS GET request; returns the HTTP status code and the decoded response payload. By default, HTTP 301, 302 and 303 are followed; all other non-2XX responses result in a urllib.error.HTTPError. If expected_code is supplied, a urllib.error.HTTPError is raised unless the status code matches expected_code. """ headers = headers or {} proxies = {'https': proxies['https']} if proxies.get('https') else {} opener = urllib.request.build_opener( urllib.request.HTTPSHandler, urllib.request.ProxyHandler(proxies), urllib.request.HTTPRedirectHandler, ) req = urllib.request.Request( url, ) resp = opener.open(req) code = resp.getcode() if expected_code is not None and code != expected_code: raise urllib.error.HTTPError(resp.geturl(), code, resp.msg, resp.info(), resp) payload = resp.read() try: payload = gzip.decompress(payload) except OSError: pass finally: payload = payload.decode('utf-8') return code, payload def https_post(url, data=None, headers=None, proxies=None, expected_code=None): """Sends an HTTPS POST request; returns the HTTP status code and the decoded response payload. By default, HTTP 301, 302 and 303 are followed; all other non-2XX responses result in a urllib.error.HTTPError. If expected_code is supplied, a urllib.error.HTTPError is raised unless the status code matches expected_code. """ data = data or {} headers = headers or {} proxies = {'https': proxies['https']} if proxies.get('https') else {} opener = urllib.request.build_opener( urllib.request.HTTPSHandler, urllib.request.ProxyHandler(proxies), urllib.request.HTTPRedirectHandler, ) req = urllib.request.Request( url, data=urllib.parse.urlencode(data).encode('ascii'), headers=headers, ) resp = opener.open(req) code = resp.getcode() if expected_code is not None and code != expected_code: raise urllib.error.HTTPError(resp.geturl(), code, resp.msg, resp.info(), resp) payload = resp.read() try: payload = gzip.decompress(payload) except OSError: pass finally: payload = payload.decode('utf-8') return code, payload def unwrap(text): """Unwrap text.""" lines = text.split('\n') result = '' for i in range(len(lines) - 1): result += lines[i] if not lines[i]: # Paragraph break result += '\n\n' elif lines[i + 1]: # Next line is not paragraph break, add space result += ' ' # Handle last line result += lines[-1] if lines[-1] else '\n' return result def check_stdout_encoding(): """Make sure stdout encoding is utf-8. If not, print error message and instructions, then exit with status 1. This function is a no-op on win32 because encoding on win32 is messy, and let's just hope for the best. /s """ if sys.platform == 'win32': return # Use codecs.lookup to resolve text encoding alias encoding = codecs.lookup(sys.stdout.encoding).name if encoding != 'utf-8': locale_lang, locale_encoding = locale.getlocale() if locale_lang is None: locale_lang = '' if locale_encoding is None: locale_encoding = '' ioencoding = os.getenv('PYTHONIOENCODING', 'not set') sys.stderr.write(unwrap(textwrap.dedent("""\ stdout encoding '{encoding}' detected. ddgr requires utf-8 to work properly. The wrong encoding may be due to a non-UTF-8 locale or an improper PYTHONIOENCODING. (For the record, your locale language is {locale_lang} and locale encoding is {locale_encoding}; your PYTHONIOENCODING is {ioencoding}.) Please set a UTF-8 locale (e.g., en_US.UTF-8) or set PYTHONIOENCODING to utf-8. """.format( encoding=encoding, locale_lang=locale_lang, locale_encoding=locale_encoding, ioencoding=ioencoding, )))) sys.exit(1) def printerr(msg): """Print message, verbatim, to stderr. ``msg`` could be any stringifiable value. """ print(msg, file=sys.stderr) # Monkeypatch textwrap for CJK wide characters. def monkeypatch_textwrap_for_cjk(): try: if textwrap.wrap.patched: return except AttributeError: pass psl_textwrap_wrap = textwrap.wrap def textwrap_wrap(text, width=70, **kwargs): if width <= 2: width = 2 # We first add a U+0000 after each East Asian Fullwidth or East # Asian Wide character, then fill to width - 1 (so that if a NUL # character ends up on a new line, we still have one last column # to spare for the preceding wide character). Finally we strip # all the NUL characters. # # East Asian Width: https://www.unicode.org/reports/tr11/ return [ line.replace('\0', '') for line in psl_textwrap_wrap( ''.join( ch + '\0' if unicodedata.east_asian_width(ch) in ('F', 'W') else ch for ch in unicodedata.normalize('NFC', text) ), width=width - 1, **kwargs ) ] def textwrap_fill(text, width=70, **kwargs): return '\n'.join(textwrap_wrap(text, width=width, **kwargs)) textwrap.wrap = textwrap_wrap textwrap.fill = textwrap_fill textwrap.wrap.patched = True textwrap.fill.patched = True monkeypatch_textwrap_for_cjk() # Classes class DdgUrl: """ This class constructs the DuckDuckGo Search/News URL. This class is modeled on urllib.parse.ParseResult for familiarity, which means it supports reading of all six attributes -- scheme, netloc, path, params, query, fragment -- of urllib.parse.ParseResult, as well as the geturl() method. However, the attributes (properties) and methods listed below should be the preferred methods of access to this class. Parameters ---------- opts : dict or argparse.Namespace, optional See the ``opts`` parameter of `update`. Other Parameters ---------------- See "Other Parameters" of `update`. Attributes ---------- hostname : str Read-write property. keywords : str or list of strs Read-write property. news : bool Read-only property. url : str Read-only property. Methods ------- full() update(opts=None, **kwargs) set_queries(**kwargs) unset_queries(*args) next_page() prev_page() first_page() """ def __init__(self, opts=None, **kwargs): self.scheme = 'https' # self.netloc is a calculated property self.path = '/html/' self.params = '' # self.query is a calculated property self.fragment = '' self._duration = '' # duration as day, week, month or unlimited self._region = '' # Region code self._qrycnt = 0 # Number of search results fetched in most recent query self._curindex = 1 # Index of total results in pages fetched so far + 1 self._page = 0 # Current page number self._keywords = [] self._sites = None self._safe = 1 # Safe search parameter value self.np_prev = '' # nextParams from last html page Previous button self.np_next = '' # nextParams from last html page Next button self._query_dict = { } self.update(opts, **kwargs) def __str__(self): return self.url @property def url(self): """The full DuckDuckGo URL you want.""" return self.full() @property def hostname(self): """The hostname.""" return self.netloc @hostname.setter def hostname(self, hostname): self.netloc = hostname @property def keywords(self): """The keywords, either a str or a list of strs.""" return self._keywords @keywords.setter def keywords(self, keywords): self._keywords = keywords @property def news(self): """Whether the URL is for DuckDuckGo News.""" return 'tbm' in self._query_dict and self._query_dict['tbm'] == 'nws' def full(self): """Return the full URL. Returns ------- str """ q = '' if self._keywords: if isinstance(self._keywords, list): q += '+'.join(list(self._keywords)) else: q += self._keywords url = (self.scheme + ':') if self.scheme else '' url += '//' + self.netloc + '/?q=' + q return url def update(self, opts=None, **kwargs): """Update the URL with the given options. Parameters ---------- opts : dict or argparse.Namespace, optional Carries options that affect the DuckDuckGo Search/News URL. The list of currently recognized option keys with expected value types: keywords: str or list of strs num: int Other Parameters ---------------- kwargs The `kwargs` dict extends `opts`, that is, options can be specified either way, in `opts` or as individual keyword arguments. """ if opts is None: opts = {} if hasattr(opts, '__dict__'): opts = opts.__dict__ opts.update(kwargs) if 'keywords' in opts: self._keywords = opts['keywords'] self._duration = opts['duration'] if 'region' in opts: self._region = opts['region'] if 'num' in opts: self._qrycnt = 0 if 'sites' in opts: self._sites = opts['sites'] if 'unsafe' in opts and opts['unsafe']: self._safe = -2 def set_queries(self, **kwargs): """Forcefully set queries outside the normal `update` mechanism. Other Parameters ---------------- kwargs Arbitrary key value pairs to be set in the query string. All keys and values should be stringifiable. Note that certain keys, e.g., ``q``, have their values constructed on the fly, so setting those has no actual effect. """ for k, v in kwargs.items(): self._query_dict[k] = v def unset_queries(self, *args): """Forcefully unset queries outside the normal `update` mechanism. Other Parameters ---------------- args Arbitrary keys to be unset. No exception is raised if a key does not exist in the first place. Note that certain keys, e.g., ``q``, are always included in the resulting URL, so unsetting those has no actual effect. """ for k in args: self._query_dict.pop(k, None) def next_page(self): """Navigate to the next page.""" self._page = self._page + 1 if self._curindex > 0: self._curindex = self._curindex + self._qrycnt else: self._curindex = -self._curindex def prev_page(self): """Navigate to the previous page. Raises ------ ValueError If already at the first page (``page=0`` in the current query string). """ if self._page == 0: raise ValueError('Already at the first page.') self._page = self._page - 1 if self._curindex > 0: self._curindex = -self._curindex # A negative index is used when fetching previous page else: self._curindex = self._curindex + self._qrycnt def first_page(self): """Navigate to the first page. Raises ------ ValueError If already at the first page (``page=0`` in the current query string). """ if self._page == 0: raise ValueError('Already at the first page.') self._page = 0 self._qrycnt = 0 self._curindex = 1 @property def netloc(self): """The hostname.""" return 'duckduckgo.com' def query(self): """The query string.""" qd = {} qd.update(self._query_dict) qd['duration'] = self._duration qd['region'] = self._region qd['curindex'] = self._curindex qd['page'] = self._page qd['safe'] = self._safe if self._curindex < 0: qd['nextParams'] = self.np_prev else: qd['nextParams'] = self.np_next # Construct the q query q = '' keywords = self._keywords sites = self._sites if keywords: if isinstance(keywords, list): q += ' '.join(list(keywords)) else: q += keywords if sites: q += ' site:' + ','.join(urllib.parse.quote_plus(site) for site in sites) qd['q'] = q return qd def update_num(self, count): self._qrycnt = count class DdgAPIUrl: """ This class constructs the DuckDuckGo Instant Answer API URL. Attributes ---------- hostname : str Read-write property. keywords : str or list of strs Read-write property. url : str Read-only property. netloc : str Read-only property. Methods ------- full() """ def __init__(self, keywords): self.scheme = 'https' self.path = '/' self.params = '' self._format = 'format=json' self._keywords = keywords def __str__(self): return self.url @property def url(self): """The full DuckDuckGo URL you want.""" return self.full() @property def hostname(self): """The hostname.""" return self.netloc @hostname.setter def hostname(self, hostname): self.netloc = hostname @property def keywords(self): """The keywords, either a str or a list of strs.""" return self._keywords @keywords.setter def keywords(self, keywords): self._keywords = keywords @property def netloc(self): """The hostname.""" return 'api.duckduckgo.com' def full(self): """Return the full URL. Returns ------- str """ q = '' if self._keywords: if isinstance(self._keywords, list): q += '+'.join(list(self._keywords)) else: q += self._keywords url = (self.scheme + ':') if self.scheme else '' url += '//' + self.netloc + '/?q=' + q + "&" + self._format return url class DDGConnectionError(Exception): pass class DdgConnection: """ This class facilitates connecting to and fetching from DuckDuckGo. Parameters ---------- See http.client.HTTPSConnection for documentation of the parameters. Raises ------ DDGConnectionError Methods ------- fetch_page(url) """ def __init__(self, proxy=None, ua=''): self._u = 'https://duckduckgo.com/html' self._proxies = { 'https': proxy if proxy is not None else (os.getenv('https_proxy') if os.getenv('https_proxy') is not None else os.getenv('HTTPS_PROXY')) } self._ua = ua def fetch_page(self, url): """Fetch a URL. Allows one reconnection and one redirection before failing and raising DDGConnectionError. Parameters ---------- url : str The URL to fetch, relative to the host. Raises ------ DDGConnectionError When not getting HTTP 200 even after the allowed one reconnection and/or one redirection, or when DuckDuckGo is blocking query due to unsual activity. Returns ------- str Response payload, gunzipped (if applicable) and decoded (in UTF-8). """ dic = url.query() page = dic['page'] LOGDBG('q:%s, region:%s, page:%d, curindex:%d, safe:%d', dic['q'], dic['region'], page, dic['curindex'], dic['safe']) LOGDBG('nextParams:%s', dic['nextParams']) LOGDBG('proxy:%s', self._proxies) LOGDBG('ua:%s', self._ua) try: if page == 0: _, r = https_post(self._u, headers={ 'Accept-Encoding': 'gzip', 'User-Agent': self._ua, 'DNT': '1', }, data={ 'q': dic['q'], 'b': '', 'df': dic['duration'], 'kf': '-1', 'kh': '1', 'kl': dic['region'], 'kp': dic['safe'], 'k1': '-1', }, proxies=self._proxies, expected_code=200) else: _, r = https_post(self._u, headers={ 'Accept-Encoding': 'gzip', 'User-Agent': self._ua, 'DNT': '1', }, data={ 'q': dic['q'], # The query string 's': str(50 * (page - 1) + 30), # Page index 'nextParams': dic['nextParams'], # nextParams from last visited page 'v': 'l', 'o': 'json', 'dc': str(dic['curindex']), # Start from total fetched result index 'df': dic['duration'], 'api': '/d.js', 'kf': '-1', # Disable favicons 'kh': '1', # HTTPS always ON 'kl': dic['region'], # Region code 'kp': dic['safe'], # Safe search 'k1': '-1', # Advertisements off }, proxies=self._proxies, expected_code=200) except Exception as e: LOGERR(e) return None return r def annotate_tag(annotated_starttag_handler): # See parser logic within the DdgParser class for documentation. # # annotated_starttag_handler(self, tag: str, attrsdict: dict) -> annotation # Returns: HTMLParser.handle_starttag(self, tag: str, attrs: list) -> None def handler(self, tag, attrs): attrs = dict(attrs) annotation = annotated_starttag_handler(self, tag, attrs) self.insert_annotation(tag, annotation) return handler def retrieve_tag_annotation(annotated_endtag_handler): # See parser logic within the DdgParser class for documentation. # # annotated_endtag_handler(self, tag: str, annotation) -> None # Returns: HTMLParser.handle_endtag(self, tag: str) -> None def handler(self, tag): try: annotation = self.tag_annotations[tag].pop() except IndexError: # Malformed HTML -- more close tags than open tags annotation = None annotated_endtag_handler(self, tag, annotation) return handler class DdgParser(html.parser.HTMLParser): """The members of this class parse the result HTML page fetched from DuckDuckGo server for a query. The custom parser looks for tags enclosing search results and extracts the URL, title and text for each search result. After parsing the complete HTML page results are returned in a list of objects of class Result. """ # Parser logic: # # - Guiding principles: # # 1. Tag handlers are contextual; # # 2. Contextual starttag and endtag handlers should come in pairs # and have a clear hierarchy; # # 3. starttag handlers should only yield control to a pair of # child handlers (that is, one level down the hierarchy), and # correspondingly, endtag handlers should only return control # to the parent (that is, the pair of handlers that gave it # control in the first place). # # Principle 3 is meant to enforce a (possibly implicit) stack # structure and thus prevent careless jumps that result in what's # essentially spaghetti code with liberal use of GOTOs. # # - HTMLParser.handle_endtag gives us a bare tag name without # context, which is not good for enforcing principle 3 when we # have, say, nested div tags. # # In order to precisely identify the matching opening tag, we # maintain a stack for each tag name with *annotations*. Important # opening tags (e.g., the ones where child handlers are # registered) can be annotated so that when we can watch for the # annotation in the endtag handler, and when the appropriate # annotation is popped, we perform the corresponding action (e.g., # switch back to old handlers). # # To facilitate this, each starttag handler is decorated with # @annotate_tag, which accepts a return value that is the # annotation (None by default), and additionally converts attrs to # a dict, which is much easier to work with; and each endtag # handler is decorated with @retrieve_tag_annotation which sends # an additional parameter that is the retrieved annotation to the # handler. # # Note that some of our tag annotation stacks leak over time: this # happens to tags like and
which are not # closed. However, these tags play no structural role, and come # only in small quantities, so it's not really a problem. # # - All textual data (result title, result abstract, etc.) are # processed through a set of shared handlers. These handlers store # text in a shared buffer self.textbuf which can be retrieved and # cleared at appropriate times. # # Data (including charrefs and entityrefs) are ignored initially, # and when data needs to be recorded, the start_populating_textbuf # method is called to register the appropriate data, charref and # entityref handlers so that they append to self.textbuf. When # recording ends, pop_textbuf should be called to extract the text # and clear the buffer. stop_populating_textbuf returns the # handlers to their pristine state (ignoring data). # # Methods: # - start_populating_textbuf(self, data_transformer: Callable[[str], str]) -> None # - pop_textbuf(self) -> str # - stop_populating_textbuf(self) -> None # # - Outermost starttag and endtag handler methods: root_*. The whole # parser starts and ends in this state. # # - Each result is wrapped in a
tag with class "links_main". # # # # # - For each result, the first

tag with class "result__title" contains the # hyperlinked title. # # #

#

# # - Abstracts are within the scope of
tag with class "links_main". Links in # abstract are ignored as they are available within

tag. # # # # # # - Each title looks like # #

# # # result title # # file type (e.g. [PDF]) # # #

def __init__(self, offset=0): html.parser.HTMLParser.__init__(self) self.title = '' self.url = '' self.abstract = '' self.filetype = '' self.results = [] self.index = offset self.textbuf = '' self.click_result = '' self.tag_annotations = {} self.np_prev_button = '' self.np_next_button = '' self.npfound = False # First next params found self.set_handlers_to('root') # Tag handlers @annotate_tag def root_start(self, tag, attrs): if tag == 'div': if 'zci__result' in self.classes(attrs): self.start_populating_textbuf() return 'click_result' if 'links_main' in self.classes(attrs): # Initialize result field registers self.title = '' self.url = '' self.abstract = '' self.filetype = '' self.set_handlers_to('result') return 'result' if 'nav-link' in self.classes(attrs): self.set_handlers_to('input') return 'input' return '' @retrieve_tag_annotation def root_end(self, tag, annotation): if annotation == 'click_result': self.stop_populating_textbuf() self.click_result = self.pop_textbuf() self.set_handlers_to('root') @annotate_tag def result_start(self, tag, attrs): if tag == 'h2' and 'result__title' in self.classes(attrs): self.set_handlers_to('title') return 'title' if tag == 'a' and 'result__snippet' in self.classes(attrs) and 'href' in attrs: self.start_populating_textbuf() return 'abstract' return '' @retrieve_tag_annotation def result_end(self, tag, annotation): if annotation == 'abstract': self.stop_populating_textbuf() self.abstract = self.pop_textbuf() elif annotation == 'result': if self.url: self.index += 1 result = Result(self.index, self.title, self.url, self.abstract, None) self.results.append(result) self.set_handlers_to('root') @annotate_tag def title_start(self, tag, attrs): if tag == 'span': # Print a space after the filetype indicator self.start_populating_textbuf(lambda text: '[' + text + ']') return 'title_filetype' if tag == 'a' and 'href' in attrs: # Skip 'News for', 'Images for' search links if attrs['href'].startswith('/search'): return '' self.url = attrs['href'] try: start = self.url.index('?q=') + len('?q=') end = self.url.index('&sa=', start) self.url = urllib.parse.unquote_plus(self.url[start:end]) except ValueError: pass self.start_populating_textbuf() return 'title_link' return '' @retrieve_tag_annotation def title_end(self, tag, annotation): if annotation == 'title_filetype': self.stop_populating_textbuf() self.filetype = self.pop_textbuf() self.start_populating_textbuf() elif annotation == 'title_link': self.stop_populating_textbuf() self.title = self.pop_textbuf() if self.filetype != '': self.title = self.filetype + self.title elif annotation == 'title': self.set_handlers_to('result') @annotate_tag def abstract_start(self, tag, attrs): if tag == 'span' and 'st' in self.classes(attrs): self.start_populating_textbuf() return 'abstract_text' return '' @retrieve_tag_annotation def abstract_end(self, tag, annotation): if annotation == 'abstract_text': self.stop_populating_textbuf() self.abstract = self.pop_textbuf() elif annotation == 'abstract': self.set_handlers_to('result') @annotate_tag def input_start(self, tag, attrs): if tag == 'input' and 'name' in attrs: if attrs['name'] == 'nextParams' and attrs['value'] != '': # The previous button always shows before next button # If there's only 1 button (page 1), it's the next button if self.npfound is True: self.np_prev_button = self.np_next_button else: self.npfound = True self.np_next_button = attrs['value'] return @retrieve_tag_annotation def input_end(self, tag, annotation): return # Generic methods # Set handle_starttag to SCOPE_start, and handle_endtag to SCOPE_end. def set_handlers_to(self, scope): self.handle_starttag = getattr(self, scope + '_start') self.handle_endtag = getattr(self, scope + '_end') def insert_annotation(self, tag, annotation): if tag not in self.tag_annotations: self.tag_annotations[tag] = [] self.tag_annotations[tag].append(annotation) def start_populating_textbuf(self, data_transformer=None): if data_transformer is None: # Record data verbatim self.handle_data = self.record_data else: def record_transformed_data(data): self.textbuf += data_transformer(data) self.handle_data = record_transformed_data self.handle_entityref = self.record_entityref self.handle_charref = self.record_charref def pop_textbuf(self): text = self.textbuf self.textbuf = '' return text def stop_populating_textbuf(self): self.handle_data = lambda data: None self.handle_entityref = lambda ref: None self.handle_charref = lambda ref: None def record_data(self, data): self.textbuf += data def record_entityref(self, ref): try: self.textbuf += chr(html.entities.name2codepoint[ref]) except KeyError: # Entity name not found; most likely rather sloppy HTML # where a literal ampersand is not escaped; For instance, # containing the following tag # #

expected market return s&p 500

# # where &p is interpreted by HTMLParser as an entity (this # behaviour seems to be specific to Python 2.7). self.textbuf += '&' + ref def record_charref(self, ref): if ref.startswith('x'): char = chr(int(ref[1:], 16)) else: char = chr(int(ref)) self.textbuf += char @staticmethod def classes(attrs): """Get tag's classes from its attribute dict.""" return attrs.get('class', '').split() def error(self, message): raise NotImplementedError("subclasses of ParserBase must override error()") Colors = collections.namedtuple('Colors', 'index, title, url, metadata, abstract, prompt, reset') class Result: """ Container for one search result, with output helpers. Parameters ---------- index : int or str title : str url : str abstract : str metadata : str, optional Only applicable to DuckDuckGo News results, with publisher name and publishing time. Attributes ---------- index : str title : str url : str abstract : str metadata : str or None Class Variables --------------- colors : str Methods ------- print() jsonizable_object() urltable() """ # Class variables colors = None urlexpand = False def __init__(self, index, title, url, abstract, metadata=None): index = str(index) self.index = index self.title = title self.url = url self.abstract = abstract self.metadata = metadata self._urltable = {index: url} def _print_title_and_url(self, index, title, url): indent = INDENT - 2 colors = self.colors if not self.urlexpand: url = '[' + urllib.parse.urlparse(url).netloc + ']' if colors: # Adjust index to print result index clearly print(" %s%-*s%s" % (colors.index, indent, index + '.', colors.reset), end='') if not self.urlexpand: print(' ' + colors.title + title + colors.reset + ' ' + colors.url + url + colors.reset) else: print(' ' + colors.title + title + colors.reset) print(' ' * (INDENT) + colors.url + url + colors.reset) else: if self.urlexpand: print(' %-*s %s' % (indent, index + '.', title)) print(' %s%s' % (' ' * (indent + 1), url)) else: print(' %-*s %s %s' % (indent, index + '.', title, url)) def _print_metadata_and_abstract(self, abstract, metadata=None): colors = self.colors try: columns, _ = os.get_terminal_size() except OSError: columns = 0 if metadata: if colors: print(' ' * INDENT + colors.metadata + metadata + colors.reset) else: print(' ' * INDENT + metadata) if colors: print(colors.abstract, end='') if columns > INDENT + 1: # Try to fill to columns fillwidth = columns - INDENT - 1 for line in textwrap.wrap(abstract.replace('\n', ''), width=fillwidth): print('%s%s' % (' ' * INDENT, line)) print('') else: print('%s\n' % abstract.replace('\n', ' ')) if colors: print(colors.reset, end='') def print(self): """Print the result entry.""" self._print_title_and_url(self.index, self.title, self.url) self._print_metadata_and_abstract(self.abstract, metadata=self.metadata) def print_paginated(self, display_index): """Print the result entry with custom index.""" self._print_title_and_url(display_index, self.title, self.url) self._print_metadata_and_abstract(self.abstract, metadata=self.metadata) def jsonizable_object(self): """Return a JSON-serializable dict representing the result entry.""" obj = { 'title': self.title, 'url': self.url, 'abstract': self.abstract } if self.metadata: obj['metadata'] = self.metadata return obj def urltable(self): """Return a index-to-URL table for the current result. Normally, the table contains only a single entry, but when the result contains sitelinks, all sitelinks are included in this table. Returns ------- dict A dict mapping indices (strs) to URLs (also strs). """ return self._urltable class DdgCmdException(Exception): pass class NoKeywordsException(DdgCmdException): pass def require_keywords(method): # Require keywords to be set before we run a DdgCmd method. If # no keywords have been set, raise a NoKeywordsException. @functools.wraps(method) def enforced_method(self, *args, **kwargs): if not self.keywords: raise NoKeywordsException('No keywords.') method(self, *args, **kwargs) return enforced_method def no_argument(method): # Normalize a do_* method of DdgCmd that takes no argument to # one that takes an arg, but issue a warning when an nonempty # argument is given. @functools.wraps(method) def enforced_method(self, arg): if arg: method_name = arg.__name__ command_name = method_name[3:] if method_name.startswith('do_') else method_name LOGGER.warning("Argument to the '%s' command ignored.", command_name) method(self) return enforced_method class DdgCmd: """ Command line interpreter and executor class for ddgr. Inspired by PSL cmd.Cmd. Parameters ---------- opts : argparse.Namespace Options and/or arguments. Attributes ---------- options : argparse.Namespace Options that are currently in effect. Read-only attribute. keywords : str or list or strs Current keywords. Read-only attribute Methods ------- fetch() display_results(prelude='\n', json_output=False) fetch_and_display(prelude='\n', json_output=False) read_next_command() help() cmdloop() """ def __init__(self, opts, ua): super().__init__() self.cmd = '' self.index = 0 self._opts = opts self._ddg_url = DdgUrl(opts) proxy = opts.proxy if hasattr(opts, 'proxy') else None self._conn = DdgConnection(proxy=proxy, ua=ua) self.results = [] self._urltable = {} colors = self.colors message = 'ddgr (? for help)' self.prompt = ((colors.prompt + message + colors.reset + ' ') if (colors and os.getenv('DISABLE_PROMPT_COLOR') is None) else (message + ': ')) @property def options(self): """Current options.""" return self._opts @property def keywords(self): """Current keywords.""" return self._ddg_url.keywords @require_keywords def fetch(self): """Fetch a page and parse for results. Results are stored in ``self.results``. Raises ------ DDGConnectionError See Also -------- fetch_and_display """ # This method also sets self._urltable. page = self._conn.fetch_page(self._ddg_url) if page is None: return if LOGGER.isEnabledFor(logging.DEBUG): fd, tmpfile = tempfile.mkstemp(prefix='ddgr-response-') os.close(fd) with open(tmpfile, 'w', encoding='utf-8') as fp: fp.write(page) LOGDBG("Response body written to '%s'.", tmpfile) if self._opts.num: _index = len(self._urltable) else: _index = 0 self._urltable = {} parser = DdgParser(offset=_index) parser.feed(page) if self._opts.num: self.results.extend(parser.results) else: self.results = parser.results for r in parser.results: self._urltable.update(r.urltable()) self._ddg_url.np_prev = parser.np_prev_button self._ddg_url.np_next = parser.np_next_button # Show instant answer if self.index == 0 and parser.click_result: if self.colors: print(self.colors.abstract) try: columns, _ = os.get_terminal_size() except OSError: columns = 0 fillwidth = columns - INDENT for line in textwrap.wrap(parser.click_result.strip(), width=fillwidth): print('%s%s' % (' ' * INDENT, line)) if self.colors: print(self.colors.reset, end='') LOGDBG('Prev nextParams: %s', self._ddg_url.np_prev) LOGDBG('Next nextParams: %s', self._ddg_url.np_next) self._ddg_url.update_num(len(parser.results)) @require_keywords def display_results(self, prelude='\n', json_output=False): """Display results stored in ``self.results``. Parameters ---------- See `fetch_and_display`. """ if self._opts.num: results = self.results[self.index:(self.index + self._opts.num)] else: results = self.results if json_output: # JSON output results_object = [r.jsonizable_object() for r in results] print(json.dumps(results_object, indent=2, sort_keys=True, ensure_ascii=False)) elif not results: print('No results.', file=sys.stderr) elif self._opts.num: # Paginated output sys.stderr.write(prelude) for i, r in enumerate(results): r.print_paginated(str(i + 1)) else: # Regular output sys.stderr.write(prelude) for r in results: r.print() @require_keywords def fetch_and_display(self, prelude='\n', json_output=False): """Fetch a page and display results. Results are stored in ``self.results``. Parameters ---------- prelude : str, optional A string that is written to stderr before showing actual results, usually serving as a separator. Default is an empty line. json_output : bool, optional Whether to dump results in JSON format. Default is False. Raises ------ DDGConnectionError See Also -------- fetch display_results """ self.fetch() self.display_results(prelude=prelude, json_output=json_output) def read_next_command(self): """Show omniprompt and read user command line. Command line is always stripped, and each consecutive group of whitespace is replaced with a single space character. If the command line is empty after stripping, when ignore it and keep reading. Exit with status 0 if we get EOF or an empty line (pre-strip, that is, a raw ) twice in a row. The new command line (non-empty) is stored in ``self.cmd``. """ enter_count = 0 while True: try: cmd = input(self.prompt) except EOFError: sys.exit(0) if not cmd: enter_count += 1 if enter_count == 2: # Double sys.exit(0) else: enter_count = 0 cmd = ' '.join(cmd.split()) if cmd: self.cmd = cmd break @staticmethod def help(): DdgArgumentParser.print_omniprompt_help(sys.stderr) printerr('') @require_keywords @no_argument def do_first(self): if self._opts.num: if self.index < self._opts.num: print('Already at the first page.', file=sys.stderr) else: self.index = 0 self.display_results() return try: self._ddg_url.first_page() except ValueError as e: print(e, file=sys.stderr) return self.fetch_and_display() def do_ddg(self, arg): if self._opts.num: self.index = 0 self.results = [] self._urltable = {} # Update keywords and reconstruct URL self._opts.keywords = arg self._ddg_url = DdgUrl(self._opts) # If there is a Bang, let DuckDuckGo do the work if arg[0] == '!' or (len(arg) > 1 and arg[1] == '!'): open_url(self._ddg_url.full()) else: self.fetch_and_display() @require_keywords @no_argument def do_next(self): if self._opts.num: count = len(self.results) if self._ddg_url._qrycnt == 0 and self.index >= count: print('No results.', file=sys.stderr) return self.index += self._opts.num if count - self.index < self._opts.num: self._ddg_url.next_page() self.fetch_and_display() else: self.display_results() elif self._ddg_url._qrycnt == 0: # If no results were fetched last time, we have hit the last page already print('No results.', file=sys.stderr) else: self._ddg_url.next_page() self.fetch_and_display() def handle_range(self, nav, low, high): try: if self._opts.num: vals = [int(x) + self.index for x in nav.split('-')] else: vals = [int(x) for x in nav.split('-')] if len(vals) != 2: printerr('Invalid range %s.' % nav) return if vals[0] > vals[1]: vals[0], vals[1] = vals[1], vals[0] for _id in range(vals[0], vals[1] + 1): if self._opts.num and _id not in range(low, high): printerr('Invalid index %s.' % (_id - self.index)) continue if str(_id) in self._urltable: open_url(self._urltable[str(_id)]) else: printerr('Invalid index %s.' % _id) except ValueError: printerr('Invalid range %s.' % nav) @require_keywords def do_open(self, low, high, *args): if not args: printerr('Index or range missing.') return for nav in args: if nav == 'a': for key, _ in sorted(self._urltable.items()): if self._opts.num and int(key) not in range(low, high): continue open_url(self._urltable[key]) elif nav in self._urltable: if self._opts.num: nav = str(int(nav) + self.index) if int(nav) not in range(low, high): printerr('Invalid index %s.' % (int(nav) - self.index)) continue open_url(self._urltable[nav]) elif '-' in nav: self.handle_range(nav, low, high) else: printerr('Invalid index %s.' % nav) @require_keywords @no_argument def do_previous(self): if self._opts.num: if self.index < self._opts.num: print('Already at the first page.', file=sys.stderr) else: self.index -= self._opts.num self.display_results() return try: self._ddg_url.prev_page() except ValueError as e: print(e, file=sys.stderr) return self.fetch_and_display() def copy_url(self, idx): try: content = self._urltable[str(idx)].encode('utf-8') # try copying the url to clipboard using native utilities copier_params = [] if sys.platform.startswith(('linux', 'freebsd', 'openbsd')): if shutil.which('xsel') is not None: copier_params = ['xsel', '-b', '-i'] elif shutil.which('xclip') is not None: copier_params = ['xclip', '-selection', 'clipboard'] # If we're using Termux (Android) use its 'termux-api' # add-on to set device clipboard. elif shutil.which('termux-clipboard-set') is not None: copier_params = ['termux-clipboard-set'] elif sys.platform == 'darwin': copier_params = ['pbcopy'] elif sys.platform == 'win32': copier_params = ['clip'] elif sys.platform.startswith('haiku'): copier_params = ['clipboard', '-i'] if copier_params: Popen(copier_params, stdin=PIPE, stdout=DEVNULL, stderr=DEVNULL).communicate(content) return # If native clipboard utilities are absent, try to use terminal multiplexers # tmux if os.getenv('TMUX_PANE'): copier_params = ['tmux', 'set-buffer'] Popen(copier_params + [content], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL).communicate() print('URL copied to tmux buffer.') return # GNU Screen paste buffer if os.getenv('STY'): copier_params = ['screen', '-X', 'readbuf', '-e', 'utf8'] tmpfd, tmppath = tempfile.mkstemp() try: with os.fdopen(tmpfd, 'wb') as fp: fp.write(content) copier_params.append(tmppath) Popen(copier_params, stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL).communicate() finally: os.unlink(tmppath) return printerr('failed to locate suitable clipboard utility') except Exception: raise NoKeywordsException def cmdloop(self): """Run REPL.""" if self.keywords: if self.keywords[0][0] == '!' or ( len(self.keywords[0]) > 1 and self.keywords[0][1] == '!' ): open_url(self._ddg_url.full()) else: self.fetch_and_display() while True: self.read_next_command() # Automatic dispatcher # # We can't write a dispatcher for now because that could # change behaviour of the prompt. However, we have already # laid a lot of ground work for the dispatcher, e.g., the # `no_argument' decorator. _num = self._opts.num try: cmd = self.cmd if cmd == 'f': self.do_first('') elif cmd.startswith('d '): self.do_ddg(cmd[2:]) elif cmd == 'n': self.do_next('') elif cmd.startswith('o '): self.do_open(self.index + 1, self.index + self._opts.num + 1, *cmd[2:].split()) elif cmd.startswith('O '): open_url.override_text_browser = True self.do_open(self.index + 1, self.index + self._opts.num + 1, *cmd[2:].split()) open_url.override_text_browser = False elif cmd == 'p': self.do_previous('') elif cmd == 'q': break elif cmd == '?': self.help() elif _num and cmd.isdigit() and int(cmd) in range(1, _num + 1): open_url(self._urltable[str(int(cmd) + self.index)]) elif _num == 0 and cmd in self._urltable: open_url(self._urltable[cmd]) elif self.keywords and cmd.isdigit() and int(cmd) < 100: printerr('Index out of bound. To search for the number, use d.') elif cmd == 'x': Result.urlexpand = not Result.urlexpand self.display_results() elif cmd.startswith('c ') and cmd[2:].isdigit(): idx = int(cmd[2:]) if 0 < idx <= min(self._opts.num, len(self._urltable)): self.copy_url(int(self.index) + idx) else: printerr("invalid index") else: self.do_ddg(cmd) except KeyError: printerr('Index out of bound. To search for the number, use d.') except NoKeywordsException: printerr('Initiate a query first.') class DdgArgumentParser(argparse.ArgumentParser): """Custom argument parser for ddgr.""" # Print omniprompt help @staticmethod def print_omniprompt_help(file=None): file = sys.stderr if file is None else file file.write(textwrap.dedent(""" omniprompt keys: n, p, f fetch the next, prev or first set of search results index open the result corresponding to index in browser o [index|range|a ...] open space-separated result indices, ranges or all O [index|range|a ...] like key 'o', but try to open in a GUI browser d keywords new DDG search for 'keywords' with original options should be used to search omniprompt keys and indices x toggle url expansion c index copy url to clipboard q, ^D, double Enter exit ddgr ? show omniprompt help * other inputs are considered as new search keywords """)) # Print information on ddgr @staticmethod def print_general_info(file=None): file = sys.stderr if file is None else file file.write(textwrap.dedent(""" Version %s Copyright © 2016-2019 Arun Prakash Jana License: GPLv3 Webpage: https://github.com/jarun/ddgr """ % _VERSION_)) # Augment print_help to print more than synopsis and options def print_help(self, file=None): super().print_help(file) self.print_omniprompt_help(file) self.print_general_info(file) # Automatically print full help text on error def error(self, message): sys.stderr.write('%s: error: %s\n\n' % (self.prog, message)) self.print_help(sys.stderr) self.exit(2) # Type guards @staticmethod def positive_int(arg): """Try to convert a string into a positive integer.""" try: n = int(arg) assert n > 0 return n except (ValueError, AssertionError): raise argparse.ArgumentTypeError('%s is not a positive integer' % arg) @staticmethod def nonnegative_int(arg): """Try to convert a string into a nonnegative integer <= 25.""" try: n = int(arg) assert n >= 0 assert n <= 25 return n except (ValueError, AssertionError): raise argparse.ArgumentTypeError('%s is not a non-negative integer <= 25' % arg) @staticmethod def is_duration(arg): """Check if a string is a valid duration accepted by DuckDuckGo. A valid duration is of the form dNUM, where d is a single letter h (hour), d (day), w (week), m (month), or y (year), and NUM is a non-negative integer. """ try: if arg[0] not in ('h', 'd', 'w', 'm', 'y') or int(arg[1:]) < 0: raise ValueError except (TypeError, IndexError, ValueError): raise argparse.ArgumentTypeError('%s is not a valid duration' % arg) return arg @staticmethod def is_colorstr(arg): """Check if a string is a valid color string.""" try: assert len(arg) == 6 for c in arg: assert c in COLORMAP except AssertionError: raise argparse.ArgumentTypeError('%s is not a valid color string' % arg) return arg # Miscellaneous functions def python_version(): return '%d.%d.%d' % sys.version_info[:3] def get_colorize(colorize): if colorize == 'always': return True if colorize == 'auto': return sys.stdout.isatty() # colorize = 'never' return False def set_win_console_mode(): # VT100 control sequences are supported on Windows 10 Anniversary Update and later. # https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences # https://docs.microsoft.com/en-us/windows/console/setconsolemode if platform.release() == '10': STD_OUTPUT_HANDLE = -11 STD_ERROR_HANDLE = -12 ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 try: from ctypes import windll, wintypes, byref kernel32 = windll.kernel32 for nhandle in (STD_OUTPUT_HANDLE, STD_ERROR_HANDLE): handle = kernel32.GetStdHandle(nhandle) old_mode = wintypes.DWORD() if not kernel32.GetConsoleMode(handle, byref(old_mode)): raise RuntimeError('GetConsoleMode failed') new_mode = old_mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING if not kernel32.SetConsoleMode(handle, new_mode): raise RuntimeError('SetConsoleMode failed') # Note: No need to restore at exit. SetConsoleMode seems to # be limited to the calling process. except Exception: pass # Query autocompleter # This function is largely experimental and could raise any exception; # you should be prepared to catch anything. When it works though, it # returns a list of strings the prefix could autocomplete to (however, # it is not guaranteed that they start with the specified prefix; for # instance, they won't if the specified prefix ends in a punctuation # mark.) def completer_fetch_completions(prefix): # One can pass the 'hl' query param to specify the language. We # ignore that for now. api_url = ('https://duckduckgo.com/ac/?q=%s&kl=wt-wt' % urllib.parse.quote(prefix, safe='')) # A timeout of 3 seconds seems to be overly generous already. resp = urllib.request.urlopen(api_url, timeout=3) respobj = json.loads(resp.read().decode('utf-8')) return [entry['phrase'] for entry in respobj] def completer_run(prefix): if prefix: completions = completer_fetch_completions('+'.join(prefix.split())) if completions: print('\n'.join(completions)) sys.exit(0) def parse_args(args=None, namespace=None): """Parse ddgr arguments/options. Parameters ---------- args : list, optional Arguments to parse. Default is ``sys.argv``. namespace : argparse.Namespace Namespace to write to. Default is a new namespace. Returns ------- argparse.Namespace Namespace with parsed arguments / options. """ colorstr_env = os.getenv('DDGR_COLORS') argparser = DdgArgumentParser(description='DuckDuckGo from the terminal.') addarg = argparser.add_argument addarg('-n', '--num', type=argparser.nonnegative_int, default=10, metavar='N', help='show N (0<=N<=25) results per page (default 10); N=0 shows actual number of results fetched per page') addarg('-r', '--reg', dest='region', default='us-en', metavar='REG', help="region-specific search e.g. 'us-en' for US (default); visit https://duckduckgo.com/params") addarg('--colorize', nargs='?', choices=['auto', 'always', 'never'], const='always', default='auto', help="""whether to colorize output; defaults to 'auto', which enables color when stdout is a tty device; using --colorize without an argument is equivalent to --colorize=always""") addarg('-C', '--nocolor', action='store_true', help='equivalent to --colorize=never') addarg('--colors', dest='colorstr', type=argparser.is_colorstr, default=colorstr_env if colorstr_env else 'oCdgxy', metavar='COLORS', help='set output colors (see man page for details)') addarg('-j', '--ducky', action='store_true', help='open the first result in a web browser; implies --np') addarg('-t', '--time', dest='duration', metavar='SPAN', default='', choices=('d', 'w', 'm'), help='time limit search ' '[d (1 day), w (1 wk), m (1 month)]') addarg('-w', '--site', dest='sites', action='append', metavar='SITE', help='search sites using DuckDuckGo') addarg('-x', '--expand', action='store_true', help='Show complete url in search results') addarg('-p', '--proxy', metavar='URI', help='tunnel traffic through an HTTPS proxy; URI format: [http[s]://][user:pwd@]host[:port]') addarg('--unsafe', action='store_true', help='disable safe search') addarg('--noua', action='store_true', help='disable user agent') addarg('--json', action='store_true', help='output in JSON format; implies --np') addarg('--gb', '--gui-browser', dest='gui_browser', action='store_true', help='open a bang directly in gui browser') addarg('--np', '--noprompt', dest='noninteractive', action='store_true', help='perform search and exit, do not prompt') addarg('--url-handler', metavar='UTIL', help='custom script or cli utility to open results') addarg('--show-browser-logs', action='store_true', help='do not suppress browser output (stdout and stderr)') addarg('-v', '--version', action='version', version=_VERSION_) addarg('-d', '--debug', action='store_true', help='enable debugging') addarg('keywords', nargs='*', metavar='KEYWORD', help='search keywords') addarg('--complete', help=argparse.SUPPRESS) parsed = argparser.parse_args(args, namespace) if parsed.nocolor: parsed.colorize = 'never' return parsed def main(): opts = parse_args() # Set logging level if opts.debug: LOGGER.setLevel(logging.DEBUG) LOGDBG('ddgr version %s Python version %s', _VERSION_, python_version()) # Handle query completer if opts.complete is not None: completer_run(opts.complete) check_stdout_encoding() # Add cmdline args to readline history if opts.keywords: try: readline.add_history(' '.join(opts.keywords)) except Exception: pass # Set colors colorize = get_colorize(opts.colorize) colors = Colors(*[COLORMAP[c] for c in opts.colorstr], reset=COLORMAP['x']) if colorize else None Result.colors = colors Result.urlexpand = opts.expand DdgCmd.colors = colors # Try to enable ANSI color support in cmd or PowerShell on Windows 10 if sys.platform == 'win32' and sys.stdout.isatty() and colorize: set_win_console_mode() if opts.url_handler is not None: open_url.url_handler = opts.url_handler else: open_url.override_text_browser = bool(opts.gui_browser) # Handle browser output suppression open_url.suppress_browser_output = not (opts.show_browser_logs or (os.getenv('BROWSER') in TEXT_BROWSERS)) try: repl = DdgCmd(opts, '' if opts.noua else USER_AGENT) if opts.json or opts.ducky or opts.noninteractive: # Non-interactive mode if repl.keywords and ( repl.keywords[0][0] == '!' or (len(repl.keywords[0]) > 1 and repl.keywords[0][1] == '!') ): # Handle bangs open_url(repl._ddg_url.full()) else: repl.fetch() if opts.ducky: if repl.results: open_url(repl.results[0].url) else: print('No results.', file=sys.stderr) else: repl.display_results(prelude='', json_output=opts.json) sys.exit(0) # Interactive mode repl.cmdloop() except Exception as e: # If debugging mode is enabled, let the exception through for a traceback; # otherwise, only print the exception error message. if LOGGER.isEnabledFor(logging.DEBUG): raise LOGERR(e) sys.exit(1) if __name__ == '__main__': main() ./.flake80000644000000000000000000000003713543566660011102 0ustar rootroot[flake8] max-line-length = 139 ./setup.py0000644000000000000000000000260613543566660011445 0ustar rootroot#!/usr/bin/env python3 import re import setuptools import shutil shutil.copyfile('ddgr', 'ddgr.py') with open('ddgr.py', encoding='utf-8') as fp: version = re.search(r'_VERSION_ = \'(.*?)\'', fp.read()).group(1) setuptools.setup( name='ddgr', version=version, url='https://github.com/jarun/ddgr', license='GPLv3', author='Arun Prakash Jana', author_email='engineerarun@gmail.com', description='DuckDuckGo from the terminal', long_description='See https://github.com/jarun/ddgr#readme.', python_requires='>=3.5', platforms=['any'], py_modules=['ddgr'], entry_points={ 'console_scripts': [ 'ddgr = ddgr:main', ], }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Internet :: WWW/HTTP :: Indexing/Search', 'Topic :: Utilities', ], ) ./Makefile0000644000000000000000000000110613543566660011365 0ustar rootrootPREFIX ?= /usr/local BINDIR ?= $(PREFIX)/bin MANDIR ?= $(PREFIX)/share/man/man1 DOCDIR ?= $(PREFIX)/share/doc/ddgr .PHONY: all install uninstall all: install: install -m755 -d $(DESTDIR)$(BINDIR) install -m755 -d $(DESTDIR)$(MANDIR) install -m755 -d $(DESTDIR)$(DOCDIR) gzip -c ddgr.1 > ddgr.1.gz install -m755 ddgr $(DESTDIR)$(BINDIR) install -m644 ddgr.1.gz $(DESTDIR)$(MANDIR) install -m644 README.md $(DESTDIR)$(DOCDIR) rm -f ddgr.1.gz uninstall: rm -f $(DESTDIR)$(BINDIR)/ddgr rm -f $(DESTDIR)$(MANDIR)/ddgr.1.gz rm -rf $(DESTDIR)$(DOCDIR) test: ./ddgr --help ./auto-completion/0000755000000000000000000000000013543566660013046 5ustar rootroot./auto-completion/bash/0000755000000000000000000000000013543566660013763 5ustar rootroot./auto-completion/bash/ddgr-completion.bash0000644000000000000000000000261513543566660017715 0ustar rootroot# # Rudimentary Bash completion definition for ddgr. # # Author: # Arun Prakash Jana # _ddgr () { COMPREPLY=() local IFS=$' \n' local cur=$2 prev=$3 local -a opts opts_with_args opts=( -h --help -n --num -r --reg -C --nocolor --colors -j --ducky -t --time -w --site -x --expand -p --proxy --unsafe --noua --json --gb --gui-browser --np --noprompt --url-handler --show-browser-logs -v --version -d --debug ) opts_with_arg=( -n --num -r --reg --colors -t --time -w --site -p --proxy --url-handler ) if [[ $cur == -* ]]; then # The current argument is an option -- complete option names. COMPREPLY=( $(compgen -W "${opts[*]}" -- "$cur") ) else # Do not complete option arguments; only autocomplete positional # arguments (queries). for opt in "${opts_with_arg[@]}"; do [[ $opt == $prev ]] && return 1 done local completion COMPREPLY=() while IFS= read -r completion; do # Quote spaces for `complete -W wordlist` COMPREPLY+=( "${completion// /\\ }" ) done < <(ddgr --complete "$cur") fi return 0 } complete -F _ddgr ddgr ./auto-completion/fish/0000755000000000000000000000000013543566660013777 5ustar rootroot./auto-completion/fish/ddgr.fish0000644000000000000000000000364213543566660015577 0ustar rootroot# # Fish completion definition for ddgr. # # Author: # Arun Prakash Jana # function __fish_ddgr_non_option_argument not string match -- "-*" (commandline -ct) end function __fish_ddgr_complete_query ddgr --complete (commandline -ct) ^/dev/null end complete -c ddgr -s h -l help --description 'show help text and exit' complete -c ddgr -s n -l num -r --description 'show N (0<=N<=25) results per page' complete -c ddgr -s r -l reg -r --description 'region-specific search' complete -c ddgr -s C -l nocolor --description 'disable color output' complete -c ddgr -l colors -r --description 'set output colors' complete -c ddgr -s j -l ducky --description 'open the first result in web browser' complete -c ddgr -s t -l time --description 'limit search duration (d/w/m)' complete -c ddgr -s w -l site -r --description 'search a site using DuckDuckGo' complete -c ddgr -s x -l expand --description 'show complete URL in results' complete -c ddgr -s p -l proxy -r --description 'specify proxy' complete -c ddgr -l unsafe --description 'disable strict search' complete -c ddgr -l noua --description 'disable user agent' complete -c ddgr -l json --description 'output in JSON format; implies --np]' complete -c ddgr -l gb -l gui-browser --description 'open a bang directly in gui browser' complete -c ddgr -l np -l noprompt --description 'perform search and exit' complete -c ddgr -l url-handler -r --description 'cli script or utility' complete -c ddgr -l show-browser-logs --description 'do not suppress browser output' complete -c ddgr -s v -l version --description 'show version number and exit' complete -c ddgr -s d -l debug --description 'enable debugging' complete -c ddgr -n __fish_ddgr_non_option_argument -a '(__fish_ddgr_complete_query)' ./auto-completion/zsh/0000755000000000000000000000000013543566660013652 5ustar rootroot./auto-completion/zsh/_ddgr0000644000000000000000000000415313543566660014657 0ustar rootroot#compdef ddgr # # Completion definition for ddgr. # # Author: # Arun Prakash Jana # setopt localoptions noshwordsplit noksharrays _ddgr_query_caching_policy () { # rebuild if cache is more than a day old local -a oldp oldp=( $1(Nm+1) ) (( $#oldp )) } _ddgr_complete_query () { local prefix=$words[CURRENT] [[ -n $prefix && $prefix != -* ]] || return local cache_id=ddgr_$prefix zstyle -s :completion:${curcontext}: cache-policy update_policy [[ -z $update_policy ]] && zstyle :completion:${curcontext}: cache_policy _ddgr_query_caching_policy local -a completions if _cache_invalid $cache_id || ! _retrieve_cache $cache_id; then completions=( ${(f)"$(ddgr --complete $prefix 2>/dev/null)"} ) _store_cache $cache_id completions fi compadd $@ -- $completions } local -a args args=( '(- : *)'{-h,--help}'[show help text and exit]' '(-n --num)'{-n,--num}'[show N (0<=N<=25) results per page]:val' '(-r --reg)'{-r,--reg}'[region-specific search]:reg-lang' '(-C --nocolor)'{-C,--nocolor}'[disable color output]' '(--colors)--colors[set output colors]:six-letter string' '(-j --ducky)'{-j,--ducky}'[open the first result in web browser]' '(-t --time)'{-t,--time}'[limit search duration]:d/w/m' '(-w --site)'{-w,--site}'[search a site using DuckDuckGo]:domain' '(-x --expand)'{-x,--expand}'[show complete URL in results]' '(-p --proxy)'{-p,--proxy}'[specify proxy]:[http[s]://][user:pwd@]host[:port]' '(--unsafe)--noua[disable strict search]' '(--noua)--noua[disable user agent]' '(--json)--json[output in JSON format; implies --np]' '(--gb --gui-browser)'{--gb,--gui-browser}'[open a bang directly in gui browser]' '(--np --noprompt)'{--np,--noprompt}'[perform search and exit]' '(--url-handler)--url-handler[cli script or utility]:url opener' '(--show-browser-logs)--show-browser-logs[do not suppress browser output]' '(- : *)'{-v,--version}'[show version number and exit]' '(-d --debug)'{-d,--debug}'[enable debugging]' '*:::query:_ddgr_complete_query' ) _arguments -S -s $args ./.pylintrc0000644000000000000000000000046513543566660011601 0ustar rootroot[MESSAGES CONTROL] disable= broad-except, invalid-name, missing-docstring, no-self-use, protected-access, too-few-public-methods, too-many-arguments, too-many-branches, too-many-function-args, too-many-instance-attributes, too-many-lines, unused-argument, [FORMAT] max-line-length=139