├── .github ├── FUNDING.yml └── workflows │ └── lock.yml ├── MANIFEST.in ├── .flake8 ├── .gitignore ├── .pylintrc ├── Makefile ├── auto-completion ├── bash │ └── ddgr-completion.bash ├── fish │ └── ddgr.fish └── zsh │ └── _ddgr ├── setup.py ├── .circleci └── config.yml ├── CHANGELOG ├── urlhandler ├── ddgr.1 ├── README.md ├── LICENSE └── ddgr /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: jarun 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include CHANGELOG LICENSE 2 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 139 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | dist/ 3 | *.bak 4 | ddgr.py 5 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [MESSAGES CONTROL] 2 | disable= 3 | broad-except, 4 | consider-using-f-string, 5 | consider-using-with, 6 | import-outside-toplevel, 7 | invalid-name, 8 | missing-docstring, 9 | no-self-use, 10 | protected-access, 11 | too-few-public-methods, 12 | too-many-arguments, 13 | too-many-branches, 14 | too-many-function-args, 15 | too-many-instance-attributes, 16 | too-many-lines, 17 | too-many-positional-arguments, 18 | too-many-statements, 19 | unused-argument, 20 | [FORMAT] 21 | max-line-length=139 22 | -------------------------------------------------------------------------------- /.github/workflows/lock.yml: -------------------------------------------------------------------------------- 1 | name: 'Lock threads' 2 | 3 | on: 4 | schedule: 5 | - cron: '0 0 * * *' 6 | workflow_dispatch: 7 | 8 | permissions: 9 | issues: write 10 | pull-requests: write 11 | discussions: write 12 | 13 | concurrency: 14 | group: lock-threads 15 | 16 | jobs: 17 | lock: 18 | runs-on: ubuntu-latest 19 | steps: 20 | - uses: dessant/lock-threads@v5 21 | with: 22 | github-token: ${{ github.token }} 23 | issue-inactive-days: '30' 24 | issue-lock-reason: '' 25 | pr-inactive-days: '30' 26 | pr-lock-reason: '' 27 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PREFIX ?= /usr/local 2 | BINDIR ?= $(PREFIX)/bin 3 | MANDIR ?= $(PREFIX)/share/man/man1 4 | DOCDIR ?= $(PREFIX)/share/doc/ddgr 5 | 6 | .PHONY: all install uninstall 7 | 8 | all: 9 | 10 | install: 11 | install -m755 -d $(DESTDIR)$(BINDIR) 12 | install -m755 -d $(DESTDIR)$(MANDIR) 13 | install -m755 -d $(DESTDIR)$(DOCDIR) 14 | gzip -c ddgr.1 > ddgr.1.gz 15 | install -m755 ddgr $(DESTDIR)$(BINDIR) 16 | install -m644 ddgr.1.gz $(DESTDIR)$(MANDIR) 17 | install -m644 README.md $(DESTDIR)$(DOCDIR) 18 | rm -f ddgr.1.gz 19 | 20 | uninstall: 21 | rm -f $(DESTDIR)$(BINDIR)/ddgr 22 | rm -f $(DESTDIR)$(MANDIR)/ddgr.1.gz 23 | rm -rf $(DESTDIR)$(DOCDIR) 24 | 25 | test: 26 | ./ddgr --help 27 | -------------------------------------------------------------------------------- /auto-completion/bash/ddgr-completion.bash: -------------------------------------------------------------------------------- 1 | # 2 | # Rudimentary Bash completion definition for ddgr. 3 | # 4 | # Author: 5 | # Arun Prakash Jana 6 | # 7 | 8 | _ddgr () { 9 | COMPREPLY=() 10 | local IFS=$' \n' 11 | local cur=$2 prev=$3 12 | local -a opts opts_with_args 13 | opts=( 14 | -h --help 15 | -n --num 16 | -r --reg 17 | -C --nocolor 18 | --colors 19 | -j --ducky 20 | -i --instant 21 | -t --time 22 | -w --site 23 | -x --expand 24 | -p --proxy 25 | --unsafe 26 | --noua 27 | --json 28 | --gb --gui-browser 29 | --np --noprompt 30 | --rev --reverse 31 | --url-handler 32 | --show-browser-logs 33 | -v --version 34 | -d --debug 35 | ) 36 | opts_with_arg=( 37 | -n --num 38 | -r --reg 39 | --colors 40 | -t --time 41 | -w --site 42 | -p --proxy 43 | --url-handler 44 | ) 45 | 46 | if [[ $cur == -* ]]; then 47 | # The current argument is an option -- complete option names. 48 | COMPREPLY=( $(compgen -W "${opts[*]}" -- "$cur") ) 49 | else 50 | # Do not complete option arguments; only autocomplete positional 51 | # arguments (queries). 52 | for opt in "${opts_with_arg[@]}"; do 53 | [[ $opt == $prev ]] && return 1 54 | done 55 | 56 | local completion 57 | COMPREPLY=() 58 | while IFS= read -r completion; do 59 | # Quote spaces for `complete -W wordlist` 60 | COMPREPLY+=( "${completion// /\\ }" ) 61 | done < <(ddgr --complete "$cur") 62 | fi 63 | 64 | return 0 65 | } 66 | 67 | complete -F _ddgr ddgr 68 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import re 4 | import os.path 5 | import setuptools 6 | import shutil 7 | 8 | if os.path.isfile('ddgr'): 9 | shutil.copyfile('ddgr', 'ddgr.py') 10 | 11 | with open('ddgr.py', encoding='utf-8') as fp: 12 | version = re.search(r'_VERSION_ = \'(.*?)\'', fp.read()).group(1) 13 | 14 | with open('README.md', encoding='utf-8') as f: 15 | long_description = f.read() 16 | 17 | setuptools.setup( 18 | name='ddgr', 19 | version=version, 20 | url='https://github.com/jarun/ddgr', 21 | license='GPLv3', 22 | license_file='LICENSE', 23 | author='Arun Prakash Jana', 24 | author_email='engineerarun@gmail.com', 25 | description='DuckDuckGo from the terminal', 26 | long_description=long_description, 27 | long_description_content_type='text/markdown', 28 | python_requires='>=3.8', 29 | platforms=['any'], 30 | py_modules=['ddgr'], 31 | entry_points={ 32 | 'console_scripts': [ 33 | 'ddgr = ddgr:main', 34 | ], 35 | }, 36 | classifiers=[ 37 | 'Development Status :: 5 - Production/Stable', 38 | 'Environment :: Console', 39 | 'Intended Audience :: Developers', 40 | 'Intended Audience :: End Users/Desktop', 41 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 42 | 'Operating System :: OS Independent', 43 | 'Programming Language :: Python', 44 | 'Programming Language :: Python :: 3', 45 | 'Programming Language :: Python :: 3 :: Only', 46 | 'Programming Language :: Python :: 3.8', 47 | 'Programming Language :: Python :: 3.9', 48 | 'Programming Language :: Python :: 3.10', 49 | 'Programming Language :: Python :: 3.11', 50 | 'Programming Language :: Python :: 3.12', 51 | 'Topic :: Internet :: WWW/HTTP :: Indexing/Search', 52 | 'Topic :: Utilities', 53 | ], 54 | ) 55 | -------------------------------------------------------------------------------- /auto-completion/fish/ddgr.fish: -------------------------------------------------------------------------------- 1 | # 2 | # Fish completion definition for ddgr. 3 | # 4 | # Author: 5 | # Arun Prakash Jana 6 | # 7 | 8 | function __fish_ddgr_non_option_argument 9 | not string match -- "-*" (commandline -ct) 10 | end 11 | 12 | function __fish_ddgr_complete_query 13 | ddgr --complete (commandline -ct) ^/dev/null 14 | end 15 | 16 | complete -c ddgr -s h -l help --description 'show help text and exit' 17 | complete -c ddgr -s n -l num -r --description 'show N (0<=N<=25) results per page' 18 | complete -c ddgr -s r -l reg -r --description 'region-specific search' 19 | complete -c ddgr -s C -l nocolor --description 'disable color output' 20 | complete -c ddgr -l colors -r --description 'set output colors' 21 | complete -c ddgr -s j -l ducky --description 'open the first result in web browser' 22 | complete -c ddgr -s i -l instant --description 'retrieve only an instant answer' 23 | complete -c ddgr -s t -l time --description 'limit search duration (d/w/m)' 24 | complete -c ddgr -s w -l site -r --description 'search a site using DuckDuckGo' 25 | complete -c ddgr -s x -l expand --description 'show complete URL in results' 26 | complete -c ddgr -s p -l proxy -r --description 'specify proxy' 27 | complete -c ddgr -l unsafe --description 'disable strict search' 28 | complete -c ddgr -l noua --description 'disable user agent' 29 | complete -c ddgr -l json --description 'output in JSON format; implies --np]' 30 | complete -c ddgr -l gb -l gui-browser --description 'open a bang directly in gui browser' 31 | complete -c ddgr -l np -l noprompt --description 'perform search and exit' 32 | complete -c ddgr -l rev -l reverse --description 'list entries in reversed order' 33 | complete -c ddgr -l url-handler -r --description 'cli script or utility' 34 | complete -c ddgr -l show-browser-logs --description 'do not suppress browser output' 35 | complete -c ddgr -s v -l version --description 'show version number and exit' 36 | complete -c ddgr -s d -l debug --description 'enable debugging' 37 | complete -c ddgr -n __fish_ddgr_non_option_argument -a '(__fish_ddgr_complete_query)' 38 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | test-template: &test-template 4 | working_directory: ~/ddgr 5 | environment: 6 | CI_FORCE_TEST: 1 7 | steps: 8 | - run: 9 | command: | 10 | apt update && apt install -y --no-install-recommends git make 11 | pip install --upgrade setuptools flake8 pylint 12 | - checkout 13 | - run: 14 | command: | 15 | python3 -m flake8 ddgr 16 | echo ddgr | xargs pylint 17 | make test 18 | 19 | jobs: 20 | py38: 21 | docker: 22 | - image: python:3.8-slim 23 | <<: *test-template 24 | 25 | py39: 26 | docker: 27 | - image: python:3.9-slim 28 | <<: *test-template 29 | 30 | py310: 31 | docker: 32 | - image: python:3.10-slim 33 | <<: *test-template 34 | 35 | py311: 36 | docker: 37 | - image: python:3.11-slim 38 | <<: *test-template 39 | 40 | py312: 41 | docker: 42 | - image: python:3.12-slim 43 | <<: *test-template 44 | 45 | # package-and-publish: 46 | # machine: true 47 | # working_directory: ~/ddgr 48 | # steps: 49 | # - checkout 50 | # - run: 51 | # name: "package with packagecore" 52 | # command: | 53 | # # Use latest installed python3 from pyenv 54 | # export PYENV_VERSION="$(pyenv versions | grep -Po '\b3\.\d+\.\d+' | tail -1)" 55 | # pip install packagecore 56 | # packagecore -o ./dist/ ${CIRCLE_TAG#v} 57 | # - run: 58 | # name: "publish to GitHub" 59 | # command: | 60 | # go get github.com/tcnksm/ghr 61 | # ghr -t ${GITHUB_API_TOKEN} -u ${CIRCLE_PROJECT_USERNAME} -r ${CIRCLE_PROJECT_REPONAME} -c ${CIRCLE_SHA1} -replace ${CIRCLE_TAG} ./dist/ 62 | 63 | workflows: 64 | version: 2 65 | 66 | CircleCI: 67 | jobs: &all-tests 68 | - py38 69 | - py39 70 | - py310 71 | - py311 72 | - py312 73 | 74 | nightly: 75 | triggers: 76 | - schedule: 77 | cron: "0 0 * * 6" 78 | filters: 79 | branches: 80 | only: 81 | - master 82 | jobs: *all-tests 83 | 84 | # publish-github-release: 85 | # jobs: 86 | # - package-and-publish: 87 | # filters: 88 | # tags: 89 | # only: /^v.*/ 90 | # branches: 91 | # ignore: /.*/ 92 | -------------------------------------------------------------------------------- /auto-completion/zsh/_ddgr: -------------------------------------------------------------------------------- 1 | #compdef ddgr 2 | # 3 | # Completion definition for ddgr. 4 | # 5 | # Author: 6 | # Arun Prakash Jana 7 | # 8 | 9 | setopt localoptions noshwordsplit noksharrays 10 | 11 | _ddgr_query_caching_policy () { 12 | # rebuild if cache is more than a day old 13 | local -a oldp 14 | oldp=( $1(Nm+1) ) 15 | (( $#oldp )) 16 | } 17 | 18 | _ddgr_complete_query () { 19 | local prefix=$words[CURRENT] 20 | [[ -n $prefix && $prefix != -* ]] || return 21 | 22 | local cache_id=ddgr_$prefix 23 | zstyle -s :completion:${curcontext}: cache-policy update_policy 24 | [[ -z $update_policy ]] && zstyle :completion:${curcontext}: cache_policy _ddgr_query_caching_policy 25 | 26 | local -a completions 27 | if _cache_invalid $cache_id || ! _retrieve_cache $cache_id; then 28 | completions=( ${(f)"$(ddgr --complete $prefix 2>/dev/null)"} ) 29 | _store_cache $cache_id completions 30 | fi 31 | 32 | compadd $@ -- $completions 33 | } 34 | 35 | local -a args 36 | args=( 37 | '(- : *)'{-h,--help}'[show help text and exit]' 38 | '(-n --num)'{-n,--num}'[show N (0<=N<=25) results per page]:val' 39 | '(-r --reg)'{-r,--reg}'[region-specific search]:reg-lang' 40 | '(-C --nocolor)'{-C,--nocolor}'[disable color output]' 41 | '(--colors)--colors[set output colors]:six-letter string' 42 | '(-j --ducky)'{-j,--ducky}'[open the first result in web browser]' 43 | '(-i --instant)'{-i,--instant}'[retrieve only an instant answer]' 44 | '(-t --time)'{-t,--time}'[limit search duration]:d/w/m' 45 | '(-w --site)'{-w,--site}'[search a site using DuckDuckGo]:domain' 46 | '(-x --expand)'{-x,--expand}'[show complete URL in results]' 47 | '(-p --proxy)'{-p,--proxy}'[specify proxy]:[http[s]://][user:pwd@]host[:port]' 48 | '(--unsafe)--noua[disable strict search]' 49 | '(--noua)--noua[disable user agent]' 50 | '(--json)--json[output in JSON format; implies --np]' 51 | '(--gb --gui-browser)'{--gb,--gui-browser}'[open a bang directly in gui browser]' 52 | '(--np --noprompt)'{--np,--noprompt}'[perform search and exit]' 53 | '(--rev --reverse)'{--rev,--reverse}'[list entries in reversed order]' 54 | '(--url-handler)--url-handler[cli script or utility]:url opener' 55 | '(--show-browser-logs)--show-browser-logs[do not suppress browser output]' 56 | '(- : *)'{-v,--version}'[show version number and exit]' 57 | '(-d --debug)'{-d,--debug}'[enable debugging]' 58 | '*:::query:_ddgr_complete_query' 59 | ) 60 | _arguments -S -s $args 61 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | ddgr v2.2 2 | 2023-12-29 3 | 4 | - Change User Agent 5 | - Discontinue Python 3.7 support (EOL) 6 | 7 | ------------------------------------------------------------------------------- 8 | 9 | ddgr v2.1 10 | 2022-10-22 11 | 12 | - Change user agent 13 | - Remove python 3.6 support 14 | - Minor documentation changes 15 | 16 | ------------------------------------------------------------------------------- 17 | 18 | ddgr v2.0 19 | 2022-03-05 20 | 21 | - Display results in reversed order (`--rev`, `--reverse`) 22 | - Support Python v3.10 (dropped v3.6) 23 | 24 | ------------------------------------------------------------------------------- 25 | 26 | ddgr v1.9 27 | 2020-07-26 28 | 29 | - Fix breakage due to changes required in POST method 30 | - Support wayland native copier `wl-copy` for url copy 31 | - Unblock GUI browsers on WSL 32 | - Update auto-generated package list 33 | - Skip broken Arch Linux packaging (https://github.com/BytePackager issue #204) 34 | 35 | ------------------------------------------------------------------------------- 36 | 37 | ddgr v1.8.1 38 | 2020-04-10 39 | 40 | - Bump version 41 | - Update docs 42 | 43 | ------------------------------------------------------------------------------- 44 | 45 | ddgr v1.8 46 | 2020-04-08 47 | 48 | What's in? 49 | - Ignore instant results in JSON output 50 | - Support year in duration 51 | - Support Python 3.8 52 | 53 | ------------------------------------------------------------------------------- 54 | 55 | ddgr v1.7 56 | 2019-09-03 57 | 58 | What's in? 59 | - Use setproctitle to set process name 60 | - Monkeypatch textwrap for CJK wide characters 61 | - Fix write to GNU Screen paste buffer 62 | - Refresh current page on URL expansion toggle 63 | - Smarter colorization and better support for native terminals on Windows 64 | - Handle bangs in the form g! 65 | 66 | ------------------------------------------------------------------------------- 67 | 68 | ddgr v1.6 69 | 2018-11-16 70 | 71 | What's in? 72 | - User interface revamped 73 | - DDG instant answers 74 | - Haiku OS clipboard support 75 | - Packaging preparation for PyPI 76 | 77 | ------------------------------------------------------------------------------- 78 | 79 | ddgr v1.5 80 | 2018-09-10 81 | 82 | What's in? 83 | - Support xclip as a clipboard utility on *nix 84 | - Support GNU Screen and tmux as clipboard fallback 85 | - Support Termux clipboard on Android 86 | 87 | ------------------------------------------------------------------------------- 88 | 89 | ddgr v1.4 90 | 2018-04-05 91 | 92 | What's in? 93 | - Copy URL at omniprompt 94 | - Check default stdout encoding at start 95 | - New environment variable DISABLE_PROMPT_COLOR 96 | 97 | ------------------------------------------------------------------------------- 98 | 99 | ddgr v1.2 100 | 2017-12-08 101 | 102 | What's in? 103 | - Remove Python3 'requests' library dependency 104 | - Remove Python 3.3 (EOL) support 105 | - Fix zsh completion script issue 106 | 107 | ------------------------------------------------------------------------------- 108 | 109 | ddgr v1.1 110 | 2017-11-29 111 | 112 | What's in? 113 | - Option `--num` to specify the number of results to show per page 114 | - Omniprompt key `x` to toggle URL expansion on-the-fly. 115 | - Option `-t` to limit search by time 116 | - Option `--gui-browser` to open bangs directly in GUI browser 117 | - Retrieve next index parameters from fetched data 118 | - Custom user agent for ddgr 119 | 120 | ------------------------------------------------------------------------------- 121 | 122 | ddgr v1.0 123 | 2017-11-05 124 | 125 | What's in? 126 | - This is the first release of `ddgr`. For a list of features visit: 127 | https://github.com/jarun/ddgr#features 128 | 129 | ------------------------------------------------------------------------------- 130 | -------------------------------------------------------------------------------- /urlhandler: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # STATIC WEB VIEWER FOR VIM CODERS that try to support all web sites in text terminal 4 | 5 | # add broken links so we can fix them 6 | broken=( 7 | https://answers.microsoft.com/en-us/windows/forum/all/ssh-login-to-microsoft-account-linked-windows/69ea0428-5b06-401c-bb86-e45228709e0b 8 | https://youtrack.jetbrains.com/issue/GO-7100/Support-commenting-in-go.mod-file 9 | https://developer.arm.com/Architectures/Valhall 10 | https://android.stackexchange.com/questions/232387/ 11 | https://www.nvidia.com/en-us/geforce/forums/legacy-products/12/182006/add-touch-screen-mapping-for-streaming-pc-games/ 12 | https://x.com/RobbyKraft/status/971534867426144257 13 | https://forums.linuxmint.com/viewtopic.php?t=374298 14 | https://www.linuxquestions.org/questions/linux-software-2/how-to-override-xrandr-minimum-screen-size-%5Bsolved%5D-4175599058/ 15 | ) 16 | 17 | function cf() { 18 | db=~/.mozilla/firefox/*.default-default/cookies.sqlite 19 | # echo "select * from moz_cookies"|sqlite3 $db|ack cf_clear| grep -o -P '(?<=cf_clearance\|).*(?=\|.stack)' 20 | echo "select * from moz_cookies"|sqlite3 $db -json|ack cf_clear|ack stack |jq -r .value 21 | 22 | # db="$HOME/.config/chromium/Default/Cookies" 23 | # echo "select * from cookies"|sqlite3 $db -json|ack cf_clear|ack stack |jq . 24 | # SELECT name,encrypted_value FROM cookie WHERE host_key = "foobar.com"; 25 | } 26 | # cf 27 | # exit 28 | 29 | isday() { 30 | read -t1 -rs -d \\ -p $'\e]11;?\e\\' bg 31 | bg=$(echo $bg | xxd -c 25 | cut -d/ -f2) 32 | if test "$(pastel format name $bg)" = white; then 33 | echo true 34 | else 35 | echo false 36 | fi 37 | } 38 | 39 | export NO_COLOR=true 40 | export GH_PAGER="vim - -MR" 41 | # if $(isday); then 42 | # export GLAMOUR_STYLE=light 43 | # else 44 | # export GLAMOUR_STYLE=dracula 45 | # fi 46 | 47 | test $TERM = screen-256color && export TERM=xterm-256color 48 | 49 | function ghraw() { 50 | local u n p 51 | # g|$vim - 52 | u=$(echo $@ | sed s,blob,raw,) 53 | n=$(basename $u) 54 | p=~/tmp 55 | test -f $p/$n || wget $u -P $p 56 | vim $p/$n 57 | } 58 | 59 | 60 | agents=( 61 | Links 62 | Lynx 63 | Gecko 64 | Firefox 65 | Chrome 66 | "Lynx/2.8.9rel.1 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/3.4.1" 67 | "Mozilla/5.0 (Android 13; Mobile; rv:133.0) Gecko/133.0 Firefox/133.0" 68 | "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36" 69 | ) 70 | 71 | # while getopts "qr" a; do 72 | car=false 73 | cro=false 74 | curl=false 75 | dump=false 76 | fox=false 77 | html=false 78 | imp=false 79 | js=false 80 | raw=false 81 | via=false 82 | x=false 83 | for a in $@; do 84 | case $a in 85 | -x) set -x 86 | x=true 87 | # shift 88 | # shift $(($OPTIND-1)) 89 | ;; 90 | -a) ag="${@: -1}"; break ;; 91 | -c) curl=true ;; 92 | -ca) car=true;; 93 | -cf) url=${broken[3]} ;; 94 | -cm) cro=true;; 95 | -d) dump=true;; 96 | -f) fox=true;; 97 | -h) html=true;; 98 | -i) imp=true;; 99 | -j) js=true;; 100 | -r) raw=true ;; 101 | -v) via=true ;; 102 | # eval "$links $u | $pager" 103 | # exit;; 104 | *) u+=$a 105 | # ((OPTIND++)) 106 | ;; 107 | esac 108 | done 109 | 110 | # remove header footer if they exist 111 | nohead() { 112 | # echo $# 113 | # exit 114 | local a b c 115 | a=$(links -dump $u) 116 | b=$(echo "$a" | sed -nr "/$1/,\$p" 2>/dev/null) 117 | if [ $# -gt 1 ]; then 118 | c=$(echo "$b" | sed "/$2/q") 119 | fi 120 | if [ -n "$c" ]; then 121 | echo "$c" | $pager 122 | elif [ -n "$b" ]; then 123 | echo "$b" | $pager 124 | else 125 | echo "$c" | $pager 126 | fi 127 | } 128 | 129 | # pager=less 130 | # nohead head 131 | # # nohead head foot 132 | # exit 133 | 134 | # parse broken pasted links 135 | # u="$u"|tr -d " \n|" 136 | if [ ! -f $u ]; then 137 | u=$(echo $u|sed "s,[\ |\n],,g"|grep -Eo 'https?://[^ ]+'|sed 's/\.$//') 138 | fi 139 | host=$(echo $u | awk -F'[/:]' '{print $4}') 140 | path=$(echo $u | gawk -F'(https?://[^/]+|?)' '$0=$2') 141 | file=$(basename $u) 142 | agent=${agents[$(($RANDOM%3))]} 143 | 144 | if $x || $curl; then 145 | echo u=$u 146 | echo host=$host 147 | echo path=$path 148 | echo file=$file 149 | echo agent=$agent 150 | # exit 151 | # read -p "open page?" 152 | fi 153 | 154 | # conf 155 | links="links -dump" 156 | # pager=less 157 | pager="vim -MR --not-a-term -" 158 | # test -n "$PAGER" && pager="$PAGER" 159 | test "$pager" = less && pager="less -+F" 160 | browser="$links \"$u\" | $pager" 161 | 162 | test -n "$ag" && curl -sLA "$ag" $u | lynx -stdin -dump | less && exit 163 | $car && carbonyl $u && exit 164 | $cro && chromium-browser --enable-logging --headless --disable-gpu --dump-dom $u|lynx -stdin -dump| less && exit 165 | $curl && curl -sL --http2 -A "$agent" $u | lynx -stdin -dump | less && exit 166 | $dump && links -dump $u && exit 167 | $fox && browsh $u && exit 168 | $html && eval "links $u" && exit 169 | $imp && curl_chrome116 -sLA Gecko $u | lynx -stdin -dump | $pager && exit 170 | $js && elinks $u -dump | eval $pager; 171 | $raw && eval "$links $u | $pager" && exit 172 | $via && termux-open-url $u mark.via.gp && exit 173 | 174 | case $host in 175 | # cloud flare 176 | x.com|askubuntu.com|*serverfault.com|*superuser.com|*stackexchange.com|stackoverflow.com) 177 | # carbonyl $u 178 | termux-open-url $u mark.via.gp 179 | exit 180 | agent='Mozilla/5.0 (X11; Linux x86_64; rv:137.0) Gecko/20100101 Firefox/137.0' 181 | # echo agent=$agent 182 | cookie="cf_clearance=$(cf)" 183 | # echo cookie=$cookie 184 | # curl -s https://$host/cdn-cgi/trace 185 | # links -dump $u | les 186 | # links -dump $u | sed -nr '/Learn more about [Labs|Teams]/,$p' | sed '/Browse other questions tagged/q' | eval $pager 187 | # curl-impersonate \ 188 | # --http2-no-server-push --alps --tls-permute-extensions --cert-compression brotli \ 189 | # curl \ 190 | # curl-impersonate \ 191 | # -H 'X-Requested-With: XMLHttpRequest' \ 192 | # -H 'sec-ch-ua-mobile: ?0' \ 193 | # -H 'Accept-Encoding: gzip, deflate, br' \ 194 | # --http2 --compressed --tlsv1.2 \ 195 | # $G/opt/curl-impersonate/bin/curl \ 196 | # curl_firefox133 \ 197 | curl_chrome124 \ 198 | -A "$agent" \ 199 | -sLv -b "$cookie" \ 200 | --referer https://$host \ 201 | $u | lynx -stdin -dump | less -F 202 | ;; 203 | 204 | # bad pre processing 205 | *ibm.com|*linux.org|linuxize.com|linux.die.net|*linuxquestions.org|*linuxmint.com|ubuntuforums.org) 206 | termux-open-url $u mark.via.gp 207 | exit 208 | agent=Gecko 209 | curl -sL --http2 -A "$agent" $u | lynx -stdin -dump | less 210 | ;; 211 | 212 | # header killer 213 | developer.android.com) 214 | case $u in 215 | *reference*) nohead 'java.lang.Object|Artifact:' 'easyToUnderstand';; 216 | *) eval $browser ;; 217 | esac ;; 218 | source.android.com) nohead 'Core Topics' 'easyToUnderstand' ;; 219 | cloud.google.com) nohead 'Transform with|Send feedback|Stay organized with collections' 'easyToUnderstand' ;; 220 | *wikipedia.org) nohead 'From Wikipedia|Other languages' ;; 221 | 222 | # custom programs 223 | gist.github*.com) gh gist view $u;; 224 | docs.github.com) links -dump $u | $pager;; 225 | github.com) 226 | case $path in 227 | *discussions*|*wiki*) nohead 'Jump to bottom|Additional navigation options|Select Topic Area' ;; 228 | # eval $browser 229 | *issues*) gh issue view --comments $u;; 230 | *pull*) gh pr view --comments $u;; 231 | # file 232 | *.*) 233 | # curl -L $(echo $u | sed s,blob,raw,) | $pager;; 234 | ghraw $u;; 235 | */*/*) gh repo view $u;; 236 | # commit links etc should fall here 237 | community*) links -dump $u | sed -n '/GitHub Community/,$p' 2>/dev/null | $pager ;; 238 | *) eval $browser ;; 239 | # GitHub Community 240 | # *) ;;& 241 | esac;; 242 | 243 | *gitlab.com) 244 | case $u in 245 | *issues*) glab issue view --comments $u;; 246 | *) glab repo view $u;; 247 | esac;; 248 | *gitlab*) 249 | case $u in 250 | *issues*) glab issue view $u;; 251 | *) glab repo view $u;; 252 | # *) eval $browser ;; 253 | esac;; 254 | 255 | *reddit.com) rtv $u ;; 256 | 257 | *stackoverflow.com) socli -o $u ;; 258 | 259 | 260 | # JavaScript never works 261 | *cyberciti.biz) elinks $u -dump | eval $pager;; 262 | 263 | # last resort ... 264 | answers.microsoft.com|developer.arm.com|quora.com|*jetbrains.com) 265 | chromium-browser --enable-logging --headless --disable-gpu --dump-dom $u|lynx -stdin -dump| $pager 266 | # read -p "open in Firefox?" y 267 | # test "$y" = y && browsh $u 268 | ;; 269 | 270 | *) eval $browser ;; 271 | esac 272 | -------------------------------------------------------------------------------- /ddgr.1: -------------------------------------------------------------------------------- 1 | .TH "DDGR" "1" "29 Dec 2023" "Version 2.2" "User Commands" 2 | .SH NAME 3 | ddgr \- DuckDuckGo from the terminal 4 | .SH SYNOPSIS 5 | .B ddgr [OPTIONS] [KEYWORD [KEYWORD ...]] 6 | .SH DESCRIPTION 7 | .B ddgr 8 | is a command-line tool to search DuckDuckGo (html version). \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. 9 | .PP 10 | .B Features 11 | .PP 12 | * Fast and clean; custom color 13 | * Designed for maximum readability at minimum space 14 | * Instant answers (supported by DDG html version) 15 | * Custom number of results per page 16 | * Navigation, browser integration 17 | * Search and option completion scripts (Bash, Fish, Zsh) 18 | * DuckDuckGo Bangs (along with completion) 19 | * Open the first result in browser (I'm Feeling Ducky) 20 | * REPL for continuous searches 21 | * Keywords (e.g. `filetype:mime`, `site:somesite.com`) 22 | * Limit search by time, specify region, disable safe search 23 | * HTTPS proxy support, optionally disable User Agent 24 | * Do Not Track set by default 25 | * Supports custom url handler script or cmdline utility 26 | * Thoroughly documented, man page with examples 27 | * Minimal dependencies 28 | .SH OPTIONS 29 | .TP 30 | .BI "-h, --help" 31 | Show help text and exit. 32 | .TP 33 | .BI "-n, --num=" N 34 | 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. 35 | .TP 36 | .BI "-r, --reg=" REG 37 | Region-specific search e.g. 'us-en' for US (default); visit https://duckduckgo.com/params. 38 | .TP 39 | .BI "-C, --nocolor" 40 | Disable color output. 41 | .TP 42 | .BI "--colors=" COLORS 43 | Set output colors. Refer to the \fBCOLORS\fR section below for details. 44 | .TP 45 | .BI "-j, --ducky" 46 | Open the first result in a web browser; implies \fB--noprompt\fR. Feeling Ducky? 47 | .TP 48 | .BI "-t, --time=" SPAN 49 | Time limit search [d=past day, w=past week, m=past month, y=past year] (default=any time). 50 | .TP 51 | .BI "-w, --site=" SITE 52 | Search a site using DuckDuckGo. 53 | .TP 54 | .BI "-x, --expand" 55 | Expand URLs instead of showing only the domain name (default). 56 | .TP 57 | .BI "-p, --proxy=" URI 58 | 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. 59 | .TP 60 | .BI "--unsafe" 61 | Disable safe search. 62 | .TP 63 | .BI "--noua" 64 | Disable user agent. Results are fetched faster. 65 | .TP 66 | .BI "--json" 67 | Output in JSON format; implies \fB--noprompt\fR. 68 | .TP 69 | .BI "-i, --instant" 70 | Retrieves only an instant answer. 71 | .TP 72 | .BI "--gb, --gui-browser" 73 | Open a bang directly in a GUI browser. 74 | .TP 75 | .BI "--np, --noprompt" 76 | Perform search and exit; do not prompt for further interactions. 77 | .TP 78 | .BI "--rev, --reverse" 79 | List the entries in reversed order. 80 | .TP 81 | .BI "--url-handler=" UTIL 82 | Custom script or command-line utility to open urls with. 83 | .TP 84 | .BI "--show-browser-logs" 85 | 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. 86 | .TP 87 | .BI "-v, --version" 88 | Show version number and exit. 89 | .TP 90 | .BI "-d, --debug" 91 | Enable debugging. 92 | .SH OMNIPROMPT KEYS 93 | .TP 94 | .BI "n, p, f" 95 | Fetch the next, previous or first set of search results. 96 | .TP 97 | .BI "index" 98 | Open the result corresponding to index in browser. 99 | .TP 100 | .BI o " [index|range|a ...]" 101 | Open space-separated result indices, numeric ranges or all indices, if 'a' is specified, in the browser. 102 | .TP 103 | .BI O " [index|range|a ...]" 104 | Works similar to key 'o', but tries to ignore text-based browsers (even if BROWSER is set) and open links in a GUI browser. 105 | .TP 106 | .BI d " keywords" 107 | Initiate a new DuckDuckGo search for \fIkeywords\fR with original options. This key should be used to search omniprompt keys (including itself) and indices. 108 | .TP 109 | .BI "x" 110 | Toggle url expansion. 111 | .TP 112 | .BI "c index" 113 | Copy url to clipboard. 114 | .TP 115 | .BI "q, ^D, double Enter" 116 | Exit ddgr. 117 | .TP 118 | .BI "?" 119 | Show omniprompt help. 120 | .TP 121 | .BI * 122 | Any other string initiates a new search with original options. 123 | .SH COLORS 124 | \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 125 | .IP - 2 126 | indices 127 | .PD 0 \" Change paragraph spacing to 0 in the list 128 | .IP - 2 129 | titles 130 | .IP - 2 131 | URLs 132 | .IP - 2 133 | metadata/publishing info 134 | .IP - 2 135 | abstracts 136 | .IP - 2 137 | prompts 138 | .PD 1 \" Restore paragraph spacing 139 | .TP 140 | 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. 141 | .TP 142 | We offer the following colors/styles: 143 | .TS 144 | tab(;) box; 145 | l|l 146 | -|- 147 | l|l. 148 | Letter;Color/Style 149 | a;black 150 | b;red 151 | c;green 152 | d;yellow 153 | e;blue 154 | f;magenta 155 | g;cyan 156 | h;white 157 | i;bright black 158 | j;bright red 159 | k;bright green 160 | l;bright yellow 161 | m;bright blue 162 | n;bright magenta 163 | o;bright cyan 164 | p;bright white 165 | A-H;bold version of the lowercase-letter color 166 | I-P;bold version of the lowercase-letter bright color 167 | x;normal 168 | X;bold 169 | y;reverse video 170 | Y;bold reverse video 171 | .TE 172 | .TP 173 | .TP 174 | The default colors string is \fIoCdgxy\fR, which stands for 175 | .IP - 2 176 | bright cyan indices 177 | .PD 0 \" Change paragraph spacing to 0 in the list 178 | .IP - 2 179 | bold green titles 180 | .IP - 2 181 | yellow URLs 182 | .IP - 2 183 | cyan metadata/publishing info 184 | .IP - 2 185 | normal abstracts 186 | .IP - 2 187 | reverse video prompts 188 | .PD 1 \" Restore paragraph spacing 189 | .TP 190 | Note that 191 | .IP - 2 192 | Bright colors (implemented as \ex1b[90m - \ex1b[97m) may not be available in all color-capable terminal emulators; 193 | .IP - 2 194 | Some terminal emulators draw bold text in bright colors instead; 195 | .IP - 2 196 | Some terminal emulators only distinguish between bold and bright colors via a default-off switch. 197 | .TP 198 | Please consult the manual of your terminal emulator as well as \fIhttps://en.wikipedia.org/wiki/ANSI_escape_code\fR for details. 199 | .SH ENVIRONMENT 200 | .TP 201 | .BI BROWSER 202 | Overrides the default browser. Ref: 203 | .I http://docs.python.org/library/webbrowser.html 204 | .TP 205 | .BI DDGR_COLORS 206 | Refer to the \fBCOLORS\fR section. 207 | .TP 208 | .BI DISABLE_PROMPT_COLOR 209 | Force a plain omniprompt if you are facing issues with colors at the prompt. 210 | .TP 211 | .BI "HTTPS_PROXY, https_proxy" 212 | Refer to the \fB--proxy\fR option. 213 | .SH EXAMPLES 214 | .PP 215 | .IP 1. 4 216 | DuckDuckGo \fBhello world\fR: 217 | .PP 218 | .EX 219 | .IP 220 | .B ddgr hello world 221 | .EE 222 | .PP 223 | .IP 2. 4 224 | \fBI'm Feeling Ducky\fR search: 225 | .PP 226 | .EX 227 | .IP 228 | .B ddgr -j lucky ducks 229 | .EE 230 | .PP 231 | .IP 3. 4 232 | \fBDuckDuckGo Bang\fR search 'hello world' in Wikipedia: 233 | .PP 234 | .EX 235 | .IP 236 | .B ddgr !w hello world 237 | .B ddgr \e!w hello world // bash-specific, need to escape ! on bash 238 | .EE 239 | .PP 240 | .IP "" 4 241 | Bangs work at the omniprompt too. To look up bangs, visit https://duckduckgo.com/bang?#bangs-list. 242 | .PP 243 | .IP 4. 4 244 | \fBBang alias\fR to fire from the cmdline, open results in a GUI browser and exit: 245 | .PP 246 | .EX 247 | .IP 248 | .B alias bang='ddgr --gb --np' 249 | .IP 250 | .B bang !w hello world 251 | .B bang \e!w hello world // bash-specific, need to escape ! on bash 252 | .EE 253 | .PP 254 | .IP 5. 4 255 | \fBWebsite specific\fR search: 256 | .PP 257 | .EX 258 | .IP 259 | .B ddgr -w amazon.com digital camera 260 | .EE 261 | .PP 262 | .IP "" 4 263 | Site specific search continues at omniprompt. 264 | .EE 265 | .PP 266 | .IP 6. 4 267 | Search for a \fBspecific file type\fR: 268 | .PP 269 | .EX 270 | .IP 271 | .B ddgr instrumental filetype:mp3 272 | .EE 273 | .PP 274 | .IP 7. 4 275 | Fetch results on IPL cricket from \fBIndia\fR in \fBEnglish\fR: 276 | .PP 277 | .EX 278 | .IP 279 | .B ddgr -r in-en IPL cricket 280 | .EE 281 | .PP 282 | .IP "" 4 283 | To find your region parameter token visit https://duckduckgo.com/params. 284 | .PP 285 | .IP 8. 4 286 | Search \fBquoted text\fR: 287 | .PP 288 | .EX 289 | .IP 290 | .B ddgr it\(rs's a \(rs\(dqbeautiful world\(rs\(dq in spring 291 | .EE 292 | .PP 293 | .IP 9. 4 294 | Show \fBcomplete urls\fR in search results (instead of only domain name): 295 | .PP 296 | .EX 297 | .IP 298 | .B ddgr -x ddgr 299 | .EE 300 | .PP 301 | .IP 10. 4 302 | Use a \fBcustom color scheme\fR, e.g., one warm color scheme designed for Solarized Dark: 303 | .PP 304 | .EX 305 | .IP 306 | .B ddgr --colors bjdxxy hello world 307 | .IP 308 | .B DDGR_COLORS=bjdxxy ddgr hello world 309 | .EE 310 | .PP 311 | .IP 11. 4 312 | Tunnel traffic through an \fBHTTPS proxy\fR, e.g., a local Privoxy instance listening on port 8118: 313 | .PP 314 | .EX 315 | .IP 316 | .B ddgr --proxy localhost:8118 hello world 317 | .EE 318 | .PP 319 | .IP "" 4 320 | By default the environment variable \fIhttps_proxy\fR (or \fIHTTPS_PROXY\fR) is used, if defined. 321 | .EE 322 | .PP 323 | .IP 12. 4 324 | 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., 325 | .PP 326 | .EX 327 | .PD 0 328 | .IP 329 | .B d n 330 | .IP 331 | .B d d keywords 332 | .IP 333 | .B d 1 334 | .PD 335 | .EE 336 | .SH AUTHOR 337 | Arun Prakash Jana 338 | .SH HOME 339 | .I https://github.com/jarun/ddgr 340 | .SH REPORTING BUGS 341 | .I https://github.com/jarun/ddgr/issues 342 | .SH LICENSE 343 | Copyright \(co 2016-2025 Arun Prakash Jana 344 | .PP 345 | License GPLv3+: GNU GPL version 3 or later . 346 | .br 347 | This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. 348 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

ddgr

2 | 3 |

4 | Latest release 5 | Availability 6 | PyPI 7 | Build Status 8 | Privacy Awareness 9 | License 10 |

11 | 12 |

13 | Asciicast 14 |

15 | 16 | `ddgr` is a cmdline utility to search DuckDuckGo ([html version](https://html.duckduckgo.com/html/)) 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! 17 | 18 | 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. 19 | 20 | A big advantage of `ddgr` over `googler` is DuckDuckGo works over the Tor network. 21 | 22 | `ddgr` isn't affiliated to DuckDuckGo in any way. 23 | 24 |

25 | Donate via PayPal! 26 |

27 | 28 | ### Table of contents 29 | 30 | - [Features](#features) 31 | - [Installation](#installation) 32 | - [Dependencies](#dependencies) 33 | - [From a package manager](#from-a-package-manager) 34 | - [From source](#from-source) 35 | - [Running standalone](#running-standalone) 36 | - [Shell completion](#shell-completion) 37 | - [Usage](#usage) 38 | - [Cmdline options](#cmdline-options) 39 | - [Configuration file](#configuration-file) 40 | - [Text-based browser integration](#text-based-browser-integration) 41 | - [Colors](#colors) 42 | - [Examples](#examples) 43 | - [Troubleshooting](#troubleshooting) 44 | - [Notes](#notes) 45 | - [Collaborators](#collaborators) 46 | - [In the Press](#in-the-press) 47 | 48 | ### Features 49 | 50 | - Fast and clean; custom color 51 | - Designed for maximum readability at minimum space 52 | - Instant answers (supported by DDG html version) 53 | - Custom number of results per page 54 | - Navigation, browser integration 55 | - Search and option completion scripts (Bash, Fish, Zsh) 56 | - DuckDuckGo Bangs (along with completion) 57 | - Open the first result in browser (I'm Feeling Ducky) 58 | - REPL for continuous searches 59 | - Keywords (e.g. `filetype:mime`, `site:somesite.com`) 60 | - Limit search by time, specify region, disable safe search 61 | - HTTPS proxy support, optionally disable User Agent 62 | - Do Not Track set by default 63 | - Supports custom url handler script or cmdline utility 64 | - Privacy-aware (no unconfirmed user data collection) 65 | - Thoroughly documented, man page with examples 66 | - Minimal dependencies 67 | 68 | ### Installation 69 | 70 | #### Dependencies 71 | 72 | `ddgr` requires Python 3.8 or later. Only the latest patch release of each minor version is supported. 73 | 74 | To copy url to clipboard at the omniprompt, `ddgr` looks for `wl-copy` (only under Wayland) or `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. 75 | 76 | Note: v1.1 and below require the Python3 `requests` library to make HTTPS requests. This dependency is removed in the later releases. 77 | 78 | #### From a package manager 79 | 80 | Install `ddgr` from your package manager. If the version available is dated try an alternative installation method. 81 | 82 |
Packaging status (expand) 83 |

84 |
85 | Packaging status 86 |

87 | Unlisted packagers: 88 |

89 |
90 | ● Awesome (awesome -install jarun/ddgr)
91 | ● PyPI (pip3 install ddgr)
92 | ● Snap Store (snap install ddgr)
93 | ● Source Mage (cast ddgr)
94 | ● Termux (pip3 install ddgr)
95 |

96 |
97 | 98 | #### From source 99 | 100 | 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). 101 | 102 | To install to the default location (`/usr/local`): 103 | 104 | $ sudo make install 105 | 106 | To remove `ddgr` and associated docs, run 107 | 108 | $ sudo make uninstall 109 | 110 | `PREFIX` is supported, in case you want to install to a different location. 111 | 112 | #### Running standalone 113 | 114 | `ddgr` is a standalone executable (and can run even on environments like Termux). From the containing directory: 115 | 116 | $ ./ddgr 117 | 118 | #### Shell completion 119 | 120 | 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. 121 | 122 | ### Usage 123 | 124 | #### Cmdline options 125 | 126 | ``` 127 | usage: ddgr [-h] [-n N] [-r REG] [--colorize [{auto,always,never}]] [-C] 128 | [--colors COLORS] [-j] [-t SPAN] [-w SITE] [-x] [-p URI] 129 | [--unsafe] [--noua] [--json] [--gb] [--np] [--url-handler UTIL] 130 | [--show-browser-logs] [-v] [-d] 131 | [KEYWORD [KEYWORD ...]] 132 | 133 | DuckDuckGo from the terminal. 134 | 135 | positional arguments: 136 | KEYWORD search keywords 137 | 138 | optional arguments: 139 | -h, --help show this help message and exit 140 | -n N, --num N show N (0<=N<=25) results per page (default 10); N=0 141 | shows actual number of results fetched per page 142 | -r REG, --reg REG region-specific search e.g. 'us-en' for US (default); 143 | visit https://duckduckgo.com/params 144 | --colorize [{auto,always,never}] 145 | whether to colorize output; defaults to 'auto', which 146 | enables color when stdout is a tty device; using 147 | --colorize without an argument is equivalent to 148 | --colorize=always 149 | -C, --nocolor equivalent to --colorize=never 150 | --colors COLORS set output colors (see man page for details) 151 | -j, --ducky open the first result in a web browser; implies --np 152 | -i, --instant retrieve only an instant answer 153 | -t SPAN, --time SPAN time limit search [d (1 day), w (1 wk), m (1 month), y (1 year)] 154 | -w SITE, --site SITE search sites using DuckDuckGo 155 | -x, --expand Show complete url in search results 156 | -p URI, --proxy URI tunnel traffic through an HTTPS proxy; URI format: 157 | [http[s]://][user:pwd@]host[:port] 158 | --unsafe disable safe search 159 | --noua disable user agent 160 | --json output in JSON format; implies --np 161 | --gb, --gui-browser open a bang directly in gui browser 162 | --np, --noprompt perform search and exit, do not prompt 163 | --rev, --reverse list entries in reversed order 164 | --url-handler UTIL custom script or cli utility to open results 165 | --show-browser-logs do not suppress browser output (stdout and stderr) 166 | -v, --version show program's version number and exit 167 | -d, --debug enable debugging 168 | 169 | omniprompt keys: 170 | n, p, f fetch the next, prev or first set of search results 171 | index open the result corresponding to index in browser 172 | o [index|range|a ...] open space-separated result indices, ranges or all 173 | O [index|range|a ...] like key 'o', but try to open in a GUI browser 174 | d keywords new DDG search for 'keywords' with original options 175 | should be used to search omniprompt keys and indices 176 | x toggle url expansion 177 | c index copy url to clipboard 178 | q, ^D, double Enter exit ddgr 179 | ? show omniprompt help 180 | * other inputs are considered as new search keywords 181 | ``` 182 | 183 | #### Configuration file 184 | 185 | `ddgr` doesn't have any! Use aliases, environment variables and auto-completion scripts. 186 | 187 | #### Text-based browser integration 188 | 189 | `ddgr` works out of the box with several text-based browsers if the `BROWSER` environment variable is set. For instance, 190 | 191 | $ export BROWSER=w3m 192 | 193 | or for one-time use, 194 | 195 | $ BROWSER=w3m ddgr query 196 | 197 | 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`. 198 | 199 | 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`. 200 | 201 | #### url handler 202 | 203 | Try the included url handler and report broken links 204 | 205 | ddgr --url-handler urlhandler 206 | 207 | #### Colors 208 | 209 | 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. 210 | 211 | ### Examples 212 | 213 | 1. DuckDuckGo **hello world**: 214 | 215 | $ ddgr hello world 216 | 2. **I'm Feeling Ducky** search: 217 | 218 | $ ddgr -j lucky ducks 219 | 3. **DuckDuckGo Bang** search `hello world` in Wikipedia: 220 | 221 | $ ddgr !w hello world 222 | $ ddgr \!w hello world // in (some) shells (e.g. bash, zsh, tcsh) '!' character need to be escaped 223 | Bangs work at the omniprompt too. To look up bangs, visit https://duckduckgo.com/bang?#bangs-list. 224 | 4. **Bang alias** to fire from the cmdline, open results in a GUI browser and exit: 225 | 226 | alias bang='ddgr --gb --np' 227 | $ bang !w hello world 228 | $ bang \!w hello world // in (some) shells (e.g. bash, zsh, tcsh) '!' character need to be escaped 229 | 5. **Website specific** search: 230 | 231 | $ ddgr -w amazon.com digital camera 232 | Site specific search continues at omniprompt. 233 | 6. Search for a **specific file type**: 234 | 235 | $ ddgr instrumental filetype:mp3 236 | 7. Fetch results on IPL cricket from **India** in **English**: 237 | 238 | $ ddgr -r in-en IPL cricket 239 | To find your region parameter token visit https://duckduckgo.com/params. 240 | 8. Search **quoted text**: 241 | 242 | $ ddgr it\'s a \"beautiful world\" in spring 243 | 9. Show **complete urls** in search results (instead of only domain name): 244 | 245 | $ ddgr -x ddgr 246 | 10. Use a **custom color scheme**, e.g., one warm color scheme designed for Solarized Dark: 247 | 248 | $ ddgr --colors bjdxxy hello world 249 | $ DDGR_COLORS=bjdxxy ddgr hello world 250 | 11. Tunnel traffic through an **HTTPS proxy**, e.g., a local Privoxy instance listening on port 8118: 251 | 252 | $ ddgr --proxy localhost:8118 hello world 253 | By default the environment variable `https_proxy` (or `HTTPS_PROXY`) is used, if defined. 254 | 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., 255 | 256 | d n 257 | d g keywords 258 | d 1 259 | 260 | ### Troubleshooting 261 | 262 | 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: 263 | 264 | export DISABLE_PROMPT_COLOR=1 265 | 266 | ### Notes 267 | 268 | 1. The Albert Launcher python plugins repo 269 | ([awesome-albert-plugins](https://github.com/bergercookie/awesome-albert-plugins)) 270 | includes suggestions-enabled search plugins for a variety of websites using 271 | `ddgr`. Refer to the latter for demos and usage instructions. 272 | 273 | ### Collaborators 274 | 275 | - [Arun Prakash Jana](https://github.com/jarun) 276 | - [Johnathan Jenkins](https://github.com/shaggytwodope) 277 | - [SZ Lin](https://github.com/szlin) 278 | - [Alex Gontar](https://github.com/mosegontar) 279 | 280 | Copyright © 2016-2025 [Arun Prakash Jana](mailto:engineerarun@gmail.com) 281 | 282 | ### In the Press 283 | 284 | - [Fossbytes](https://fossbytes.com/search-duckduckgo-from-terminal-ddgr/) 285 | - [Hacker News](https://news.ycombinator.com/item?id=19606101) 286 | - [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/) 287 | - [LinOxide](https://linoxide.com/tools/search-duckduckgo-command-line/) 288 | - [OMG! Ubuntu!](http://www.omgubuntu.co.uk/2017/11/duck-duck-go-terminal-app) 289 | - [Tecmint](https://www.tecmint.com/search-duckduckgo-from-linux-terminal/) 290 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /ddgr: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Copyright (C) 2016-2025 Arun Prakash Jana 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | import argparse 19 | import codecs 20 | import collections 21 | import functools 22 | import gzip 23 | import html.entities 24 | import html.parser 25 | import json 26 | import locale 27 | import logging 28 | import os 29 | import platform 30 | import shutil 31 | import signal 32 | from subprocess import Popen, PIPE, DEVNULL 33 | import sys 34 | import tempfile 35 | import textwrap 36 | import unicodedata 37 | import urllib.error 38 | import urllib.parse 39 | import urllib.request 40 | import webbrowser 41 | 42 | try: 43 | import readline 44 | except ImportError: 45 | pass 46 | 47 | try: 48 | import setproctitle 49 | setproctitle.setproctitle('ddgr') 50 | except (ImportError, Exception): 51 | pass 52 | 53 | # Basic setup 54 | 55 | logging.basicConfig(format='[%(levelname)s] %(message)s') 56 | LOGGER = logging.getLogger() 57 | LOGDBG = LOGGER.debug 58 | LOGERR = LOGGER.error 59 | 60 | 61 | def sigint_handler(signum, frame): 62 | print('\nInterrupted.', file=sys.stderr) 63 | sys.exit(1) 64 | 65 | 66 | try: 67 | signal.signal(signal.SIGINT, sigint_handler) 68 | except ValueError: 69 | # signal only works in main thread 70 | pass 71 | 72 | # Constants 73 | 74 | _VERSION_ = '2.2' 75 | 76 | COLORMAP = {k: '\x1b[%sm' % v for k, v in { 77 | 'a': '30', 'b': '31', 'c': '32', 'd': '33', 78 | 'e': '34', 'f': '35', 'g': '36', 'h': '37', 79 | 'i': '90', 'j': '91', 'k': '92', 'l': '93', 80 | 'm': '94', 'n': '95', 'o': '96', 'p': '97', 81 | 'A': '30;1', 'B': '31;1', 'C': '32;1', 'D': '33;1', 82 | 'E': '34;1', 'F': '35;1', 'G': '36;1', 'H': '37;1', 83 | 'I': '90;1', 'J': '91;1', 'K': '92;1', 'L': '93;1', 84 | 'M': '94;1', 'N': '95;1', 'O': '96;1', 'P': '97;1', 85 | 'x': '0', 'X': '1', 'y': '7', 'Y': '7;1', 86 | }.items()} 87 | 88 | USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' 89 | 90 | TEXT_BROWSERS = ['elinks', 'links', 'lynx', 'w3m', 'www-browser'] 91 | 92 | INDENT = 5 93 | 94 | 95 | # Global helper functions 96 | def make_safe_url(url: str) -> str: 97 | """ 98 | Convert a URL with Unicode characters into a browser-safe ASCII URL. 99 | 100 | International domain names converted Punycode 101 | Everything else is percent-encoded. 102 | """ 103 | parts = urllib.parse.urlsplit(url) 104 | 105 | hostname = parts.hostname 106 | if hostname: 107 | try: 108 | hostname = hostname.encode("idna").decode("ascii") 109 | except UnicodeError: 110 | pass 111 | 112 | netloc = "" 113 | 114 | if parts.username: 115 | netloc += urllib.parse.quote(parts.username) 116 | if parts.password: 117 | netloc += ":" + urllib.parse.quote(parts.password) 118 | netloc += "@" 119 | 120 | if hostname: 121 | netloc += hostname 122 | 123 | if parts.port: 124 | netloc += f":{parts.port}" 125 | 126 | path = urllib.parse.quote(parts.path) 127 | query = urllib.parse.quote(parts.query, safe="=&") 128 | fragment = urllib.parse.quote(parts.fragment) 129 | 130 | return urllib.parse.urlunsplit((parts.scheme, netloc, path, query, fragment)) 131 | 132 | 133 | def open_url(url): 134 | """Open an URL in the user's default web browser. 135 | 136 | The string attribute ``open_url.url_handler`` can be used to open URLs 137 | in a custom CLI script or utility. A subprocess is spawned with url as 138 | the parameter in this case instead of the usual webbrowser.open() call. 139 | 140 | Whether the browser's output (both stdout and stderr) are suppressed 141 | depends on the boolean attribute ``open_url.suppress_browser_output``. 142 | If the attribute is not set upon a call, set it to a default value, 143 | which means False if BROWSER is set to a known text-based browser -- 144 | elinks, links, lynx, w3m or 'www-browser'; or True otherwise. 145 | 146 | The string attribute ``open_url.override_text_browser`` can be used to 147 | ignore env var BROWSER as well as some known text-based browsers and 148 | attempt to open url in a GUI browser available. 149 | Note: If a GUI browser is indeed found, this option ignores the program 150 | option `show-browser-logs` 151 | """ 152 | LOGDBG('Opening %s', url) 153 | 154 | # Safe approach to unicode in URL 155 | safe_url = make_safe_url(url) 156 | if url != safe_url: 157 | LOGDBG('Opening unicode-safe URL: %s', safe_url) 158 | 159 | # Custom URL handler gets max priority 160 | if hasattr(open_url, 'url_handler'): 161 | with Popen([open_url.url_handler, safe_url], stdin=PIPE) as pipe: 162 | pipe.communicate() 163 | return 164 | 165 | browser = webbrowser.get() 166 | if open_url.override_text_browser: 167 | browser_output = open_url.suppress_browser_output 168 | for name in [b for b in webbrowser._tryorder if b not in TEXT_BROWSERS]: 169 | browser = webbrowser.get(name) 170 | LOGDBG(browser) 171 | 172 | # Found a GUI browser, suppress browser output 173 | open_url.suppress_browser_output = True 174 | break 175 | 176 | if open_url.suppress_browser_output: 177 | _stderr = os.dup(2) 178 | os.close(2) 179 | _stdout = os.dup(1) 180 | if "microsoft" not in platform.uname()[3].lower(): 181 | os.close(1) 182 | fd = os.open(os.devnull, os.O_RDWR) 183 | os.dup2(fd, 2) 184 | os.dup2(fd, 1) 185 | try: 186 | browser.open(safe_url, new=2) 187 | finally: 188 | if open_url.suppress_browser_output: 189 | os.close(fd) 190 | os.dup2(_stderr, 2) 191 | os.dup2(_stdout, 1) 192 | 193 | if open_url.override_text_browser: 194 | open_url.suppress_browser_output = browser_output 195 | 196 | 197 | def https_get(url, headers=None, proxies=None, expected_code=None): 198 | """Sends an HTTPS GET request; returns the HTTP status code and the 199 | decoded response payload. 200 | 201 | By default, HTTP 301, 302 and 303 are followed; all other non-2XX 202 | responses result in a urllib.error.HTTPError. If expected_code is 203 | supplied, a urllib.error.HTTPError is raised unless the status code 204 | matches expected_code. 205 | """ 206 | headers = headers or {} 207 | proxies = {'https': proxies['https']} if proxies.get('https') else {} 208 | opener = urllib.request.build_opener( 209 | urllib.request.HTTPSHandler, 210 | urllib.request.ProxyHandler(proxies), 211 | urllib.request.HTTPRedirectHandler, 212 | ) 213 | req = urllib.request.Request( 214 | url, 215 | ) 216 | resp = opener.open(req) 217 | code = resp.getcode() 218 | if expected_code is not None and code != expected_code: 219 | raise urllib.error.HTTPError(resp.geturl(), code, resp.msg, resp.info(), resp) 220 | payload = resp.read() 221 | try: 222 | payload = gzip.decompress(payload) 223 | except OSError: 224 | pass 225 | finally: 226 | payload = payload.decode('utf-8') 227 | return code, payload 228 | 229 | 230 | def https_post(url, data=None, headers=None, proxies=None, expected_code=None): 231 | """Sends an HTTPS POST request; returns the HTTP status code and the 232 | decoded response payload. 233 | 234 | By default, HTTP 301, 302 and 303 are followed; all other non-2XX 235 | responses result in a urllib.error.HTTPError. If expected_code is 236 | supplied, a urllib.error.HTTPError is raised unless the status code 237 | matches expected_code. 238 | """ 239 | data = data or {} 240 | headers = headers or {} 241 | proxies = {'https': proxies['https']} if proxies.get('https') else {} 242 | opener = urllib.request.build_opener( 243 | urllib.request.HTTPSHandler, 244 | urllib.request.ProxyHandler(proxies), 245 | urllib.request.HTTPRedirectHandler, 246 | ) 247 | req = urllib.request.Request( 248 | url, 249 | data=urllib.parse.urlencode(data).encode('ascii'), 250 | headers=headers, 251 | ) 252 | resp = opener.open(req) 253 | code = resp.getcode() 254 | if expected_code is not None and code != expected_code: 255 | raise urllib.error.HTTPError(resp.geturl(), code, resp.msg, resp.info(), resp) 256 | payload = resp.read() 257 | try: 258 | payload = gzip.decompress(payload) 259 | except OSError: 260 | pass 261 | finally: 262 | payload = payload.decode('utf-8') 263 | return code, payload 264 | 265 | 266 | def unwrap(text): 267 | """Unwrap text.""" 268 | lines = text.split('\n') 269 | result = '' 270 | for i in range(len(lines) - 1): 271 | result += lines[i] 272 | if not lines[i]: 273 | # Paragraph break 274 | result += '\n\n' 275 | elif lines[i + 1]: 276 | # Next line is not paragraph break, add space 277 | result += ' ' 278 | # Handle last line 279 | result += lines[-1] if lines[-1] else '\n' 280 | return result 281 | 282 | 283 | def check_stdout_encoding(): 284 | """Make sure stdout encoding is utf-8. 285 | 286 | If not, print error message and instructions, then exit with 287 | status 1. 288 | 289 | This function is a no-op on win32 because encoding on win32 is 290 | messy, and let's just hope for the best. /s 291 | """ 292 | if sys.platform == 'win32': 293 | return 294 | 295 | # Use codecs.lookup to resolve text encoding alias 296 | encoding = codecs.lookup(sys.stdout.encoding).name 297 | if encoding != 'utf-8': 298 | locale_lang, locale_encoding = locale.getlocale() 299 | if locale_lang is None: 300 | locale_lang = '' 301 | if locale_encoding is None: 302 | locale_encoding = '' 303 | ioencoding = os.getenv('PYTHONIOENCODING', 'not set') 304 | sys.stderr.write(unwrap(textwrap.dedent("""\ 305 | stdout encoding '{encoding}' detected. ddgr requires utf-8 to 306 | work properly. The wrong encoding may be due to a non-UTF-8 307 | locale or an improper PYTHONIOENCODING. (For the record, your 308 | locale language is {locale_lang} and locale encoding is 309 | {locale_encoding}; your PYTHONIOENCODING is {ioencoding}.) 310 | 311 | Please set a UTF-8 locale (e.g., en_US.UTF-8) or set 312 | PYTHONIOENCODING to utf-8. 313 | """.format( 314 | encoding=encoding, 315 | locale_lang=locale_lang, 316 | locale_encoding=locale_encoding, 317 | ioencoding=ioencoding, 318 | )))) 319 | sys.exit(1) 320 | 321 | 322 | def printerr(msg): 323 | """Print message, verbatim, to stderr. 324 | 325 | ``msg`` could be any stringifiable value. 326 | """ 327 | print(msg, file=sys.stderr) 328 | 329 | 330 | # Monkeypatch textwrap for CJK wide characters. 331 | def monkeypatch_textwrap_for_cjk(): 332 | try: 333 | if textwrap.wrap.patched: 334 | return 335 | except AttributeError: 336 | pass 337 | psl_textwrap_wrap = textwrap.wrap 338 | 339 | def textwrap_wrap(text, width=70, **kwargs): 340 | width = max(width, 2) 341 | # We first add a U+0000 after each East Asian Fullwidth or East 342 | # Asian Wide character, then fill to width - 1 (so that if a NUL 343 | # character ends up on a new line, we still have one last column 344 | # to spare for the preceding wide character). Finally we strip 345 | # all the NUL characters. 346 | # 347 | # East Asian Width: https://www.unicode.org/reports/tr11/ 348 | return [ 349 | line.replace('\0', '') 350 | for line in psl_textwrap_wrap( 351 | ''.join( 352 | ch + '\0' if unicodedata.east_asian_width(ch) in ('F', 'W') else ch 353 | for ch in unicodedata.normalize('NFC', text) 354 | ), 355 | width=width - 1, 356 | **kwargs 357 | ) 358 | ] 359 | 360 | def textwrap_fill(text, width=70, **kwargs): 361 | return '\n'.join(textwrap_wrap(text, width=width, **kwargs)) 362 | textwrap.wrap = textwrap_wrap 363 | textwrap.fill = textwrap_fill 364 | textwrap.wrap.patched = True 365 | textwrap.fill.patched = True 366 | 367 | 368 | monkeypatch_textwrap_for_cjk() 369 | 370 | 371 | # Classes 372 | 373 | class DdgUrl: 374 | """ 375 | This class constructs the DuckDuckGo Search/News URL. 376 | 377 | This class is modeled on urllib.parse.ParseResult for familiarity, 378 | which means it supports reading of all six attributes -- scheme, 379 | netloc, path, params, query, fragment -- of 380 | urllib.parse.ParseResult, as well as the geturl() method. 381 | 382 | However, the attributes (properties) and methods listed below should 383 | be the preferred methods of access to this class. 384 | 385 | Parameters 386 | ---------- 387 | opts : dict or argparse.Namespace, optional 388 | See the ``opts`` parameter of `update`. 389 | 390 | Other Parameters 391 | ---------------- 392 | See "Other Parameters" of `update`. 393 | 394 | Attributes 395 | ---------- 396 | hostname : str 397 | Read-write property. 398 | keywords : str or list of strs 399 | Read-write property. 400 | news : bool 401 | Read-only property. 402 | url : str 403 | Read-only property. 404 | 405 | Methods 406 | ------- 407 | full() 408 | update(opts=None, **kwargs) 409 | set_queries(**kwargs) 410 | unset_queries(*args) 411 | next_page() 412 | prev_page() 413 | first_page() 414 | 415 | """ 416 | 417 | def __init__(self, opts=None, **kwargs): 418 | self.scheme = 'https' 419 | # self.netloc is a calculated property 420 | self.path = '/html/' 421 | self.params = '' 422 | # self.query is a calculated property 423 | self.fragment = '' 424 | 425 | self._duration = '' # duration as day, week, month or unlimited 426 | self._region = '' # Region code 427 | self._qrycnt = 0 # Number of search results fetched in most recent query 428 | self._curindex = 1 # Index of total results in pages fetched so far + 1 429 | self._page = 0 # Current page number 430 | self._keywords = [] 431 | self._sites = None 432 | self._safe = 1 # Safe search parameter value 433 | self.np_prev = '' # nextParams from last html page Previous button 434 | self.np_next = '' # nextParams from last html page Next button 435 | self.vqd = '' # vqd parameter (from next/prev button) 436 | self._query_dict = { 437 | } 438 | self.update(opts, **kwargs) 439 | 440 | def __str__(self): 441 | return self.url 442 | 443 | @property 444 | def url(self): 445 | """The full DuckDuckGo URL you want.""" 446 | return self.full() 447 | 448 | @property 449 | def hostname(self): 450 | """The hostname.""" 451 | return self.netloc 452 | 453 | @hostname.setter 454 | def hostname(self, hostname): 455 | self.netloc = hostname 456 | 457 | @property 458 | def keywords(self): 459 | """The keywords, either a str or a list of strs.""" 460 | return self._keywords 461 | 462 | @keywords.setter 463 | def keywords(self, keywords): 464 | self._keywords = keywords 465 | 466 | @property 467 | def news(self): 468 | """Whether the URL is for DuckDuckGo News.""" 469 | return 'tbm' in self._query_dict and self._query_dict['tbm'] == 'nws' 470 | 471 | def full(self): 472 | """Return the full URL. 473 | 474 | Returns 475 | ------- 476 | str 477 | 478 | """ 479 | q = '' 480 | if self._keywords: 481 | if isinstance(self._keywords, list): 482 | q += '+'.join(list(self._keywords)) 483 | else: 484 | q += self._keywords 485 | 486 | url = (self.scheme + ':') if self.scheme else '' 487 | url += '//' + self.netloc + '/?q=' + q 488 | return url 489 | 490 | def update(self, opts=None, **kwargs): 491 | """Update the URL with the given options. 492 | 493 | Parameters 494 | ---------- 495 | opts : dict or argparse.Namespace, optional 496 | Carries options that affect the DuckDuckGo Search/News URL. The 497 | list of currently recognized option keys with expected value 498 | types: 499 | 500 | keywords: str or list of strs 501 | num: int 502 | 503 | Other Parameters 504 | ---------------- 505 | kwargs 506 | The `kwargs` dict extends `opts`, that is, options can be 507 | specified either way, in `opts` or as individual keyword 508 | arguments. 509 | 510 | """ 511 | 512 | if opts is None: 513 | opts = {} 514 | if hasattr(opts, '__dict__'): 515 | opts = opts.__dict__ 516 | opts.update(kwargs) 517 | 518 | if 'keywords' in opts: 519 | self._keywords = opts['keywords'] 520 | self._duration = opts['duration'] 521 | if 'region' in opts: 522 | self._region = opts['region'] 523 | if 'num' in opts: 524 | self._qrycnt = 0 525 | if 'sites' in opts: 526 | self._sites = opts['sites'] 527 | if 'unsafe' in opts and opts['unsafe']: 528 | self._safe = -2 529 | 530 | def set_queries(self, **kwargs): 531 | """Forcefully set queries outside the normal `update` mechanism. 532 | 533 | Other Parameters 534 | ---------------- 535 | kwargs 536 | Arbitrary key value pairs to be set in the query string. All 537 | keys and values should be stringifiable. 538 | 539 | Note that certain keys, e.g., ``q``, have their values 540 | constructed on the fly, so setting those has no actual 541 | effect. 542 | 543 | """ 544 | for k, v in kwargs.items(): 545 | self._query_dict[k] = v 546 | 547 | def unset_queries(self, *args): 548 | """Forcefully unset queries outside the normal `update` mechanism. 549 | 550 | Other Parameters 551 | ---------------- 552 | args 553 | Arbitrary keys to be unset. No exception is raised if a key 554 | does not exist in the first place. 555 | 556 | Note that certain keys, e.g., ``q``, are always included in 557 | the resulting URL, so unsetting those has no actual effect. 558 | 559 | """ 560 | for k in args: 561 | self._query_dict.pop(k, None) 562 | 563 | def next_page(self): 564 | """Navigate to the next page.""" 565 | self._page = self._page + 1 566 | 567 | if self._curindex > 0: 568 | self._curindex = self._curindex + self._qrycnt 569 | else: 570 | self._curindex = -self._curindex 571 | 572 | def prev_page(self): 573 | """Navigate to the previous page. 574 | 575 | Raises 576 | ------ 577 | ValueError 578 | If already at the first page (``page=0`` in the current 579 | query string). 580 | 581 | """ 582 | if self._page == 0: 583 | raise ValueError('Already at the first page.') 584 | 585 | self._page = self._page - 1 586 | 587 | if self._curindex > 0: 588 | self._curindex = -self._curindex # A negative index is used when fetching previous page 589 | else: 590 | self._curindex = self._curindex + self._qrycnt 591 | 592 | def first_page(self): 593 | """Navigate to the first page. 594 | 595 | Raises 596 | ------ 597 | ValueError 598 | If already at the first page (``page=0`` in the current 599 | query string). 600 | 601 | """ 602 | if self._page == 0: 603 | raise ValueError('Already at the first page.') 604 | self._page = 0 605 | self._qrycnt = 0 606 | self._curindex = 1 607 | 608 | @property 609 | def netloc(self): 610 | """The hostname.""" 611 | return 'duckduckgo.com' 612 | 613 | def query(self): 614 | """The query string.""" 615 | qd = {} 616 | qd.update(self._query_dict) 617 | qd['duration'] = self._duration 618 | qd['region'] = self._region 619 | qd['curindex'] = self._curindex 620 | qd['page'] = self._page 621 | qd['safe'] = self._safe 622 | if self._curindex < 0: 623 | qd['nextParams'] = self.np_prev 624 | else: 625 | qd['nextParams'] = self.np_next 626 | qd['vqd'] = self.vqd 627 | 628 | # Construct the q query 629 | q = '' 630 | keywords = self._keywords 631 | sites = self._sites 632 | if keywords: 633 | if isinstance(keywords, list): 634 | q += ' '.join(list(keywords)) 635 | else: 636 | q += keywords 637 | if sites: 638 | q += ' (' 639 | for site in sites: 640 | q += ' site:' + urllib.parse.quote_plus(site) + ' OR' 641 | q += ' )' 642 | qd['q'] = q 643 | 644 | return qd 645 | 646 | def update_num(self, count): 647 | self._qrycnt = count 648 | 649 | 650 | class DdgAPIUrl: 651 | """ 652 | This class constructs the DuckDuckGo Instant Answer API URL. 653 | 654 | Attributes 655 | ---------- 656 | hostname : str 657 | Read-write property. 658 | keywords : str or list of strs 659 | Read-write property. 660 | url : str 661 | Read-only property. 662 | netloc : str 663 | Read-only property. 664 | 665 | Methods 666 | ------- 667 | full() 668 | 669 | """ 670 | 671 | def __init__(self, keywords): 672 | self.scheme = 'https' 673 | self.path = '/' 674 | self.params = '' 675 | self._format = 'format=json' 676 | self._keywords = keywords 677 | 678 | def __str__(self): 679 | return self.url 680 | 681 | @property 682 | def url(self): 683 | """The full DuckDuckGo URL you want.""" 684 | return self.full() 685 | 686 | @property 687 | def hostname(self): 688 | """The hostname.""" 689 | return self.netloc 690 | 691 | @hostname.setter 692 | def hostname(self, hostname): 693 | self.netloc = hostname 694 | 695 | @property 696 | def keywords(self): 697 | """The keywords, either a str or a list of strs.""" 698 | return self._keywords 699 | 700 | @keywords.setter 701 | def keywords(self, keywords): 702 | self._keywords = keywords 703 | 704 | @property 705 | def netloc(self): 706 | """The hostname.""" 707 | return 'api.duckduckgo.com' 708 | 709 | def full(self): 710 | """Return the full URL. 711 | 712 | Returns 713 | ------- 714 | str 715 | 716 | """ 717 | q = '' 718 | if self._keywords: 719 | if isinstance(self._keywords, list): 720 | q += '+'.join(list(self._keywords)) 721 | else: 722 | q += self._keywords 723 | 724 | url = (self.scheme + ':') if self.scheme else '' 725 | url += '//' + self.netloc + '/?q=' + q + "&" + self._format 726 | return url 727 | 728 | 729 | class DDGConnectionError(Exception): 730 | pass 731 | 732 | 733 | class DdgConnection: 734 | """ 735 | This class facilitates connecting to and fetching from DuckDuckGo. 736 | 737 | Parameters 738 | ---------- 739 | See http.client.HTTPSConnection for documentation of the 740 | parameters. 741 | 742 | Raises 743 | ------ 744 | DDGConnectionError 745 | 746 | Methods 747 | ------- 748 | fetch_page(url) 749 | 750 | """ 751 | 752 | def __init__(self, proxy=None, ua=''): 753 | self._u = 'https://html.duckduckgo.com/html' 754 | 755 | self._proxies = { 756 | 'https': proxy if proxy is not None else (os.getenv('https_proxy') 757 | if os.getenv('https_proxy') is not None 758 | else os.getenv('HTTPS_PROXY')) 759 | } 760 | self._ua = ua 761 | 762 | def fetch_page(self, url): 763 | """Fetch a URL. 764 | 765 | Allows one reconnection and one redirection before failing and 766 | raising DDGConnectionError. 767 | 768 | Parameters 769 | ---------- 770 | url : str 771 | The URL to fetch, relative to the host. 772 | 773 | Raises 774 | ------ 775 | DDGConnectionError 776 | When not getting HTTP 200 even after the allowed one 777 | reconnection and/or one redirection, or when DuckDuckGo is 778 | blocking query due to unusual activity. 779 | 780 | Returns 781 | ------- 782 | str 783 | Response payload, gunzipped (if applicable) and decoded (in UTF-8). 784 | 785 | """ 786 | dic = url.query() 787 | page = dic['page'] 788 | LOGDBG('q:%s, region:%s, page:%d, curindex:%d, safe:%d', dic['q'], dic['region'], page, dic['curindex'], dic['safe']) 789 | LOGDBG('nextParams:%s', dic['nextParams']) 790 | LOGDBG('vqd:%s', dic['vqd']) 791 | LOGDBG('proxy:%s', self._proxies) 792 | LOGDBG('ua:%s', self._ua) 793 | 794 | try: 795 | if page == 0: 796 | _, r = https_post(self._u, 797 | headers={ 798 | 'Accept-Encoding': 'gzip', 799 | 'User-Agent': self._ua, 800 | 'DNT': '1', 801 | }, 802 | data={ 803 | 'q': dic['q'], 804 | 'b': '', 805 | 'df': dic['duration'], 806 | 'kf': '-1', 807 | 'kh': '1', 808 | 'kl': dic['region'], 809 | 'kp': dic['safe'], 810 | 'k1': '-1', 811 | }, 812 | proxies=self._proxies, 813 | expected_code=200) 814 | else: 815 | _, r = https_post(self._u, 816 | headers={ 817 | 'Accept-Encoding': 'gzip', 818 | 'User-Agent': self._ua, 819 | 'DNT': '1', 820 | }, 821 | data={ 822 | 'q': dic['q'], # The query string 823 | 's': str(50 * (page - 1) + 30), # Page index 824 | 'nextParams': dic['nextParams'], # nextParams from last visited page 825 | 'v': 'l', 826 | 'o': 'json', 827 | 'dc': str(dic['curindex']), # Start from total fetched result index 828 | 'df': dic['duration'], 829 | 'api': '/d.js', 830 | 'kf': '-1', # Disable favicons 831 | 'kh': '1', # HTTPS always ON 832 | 'kl': dic['region'], # Region code 833 | 'kp': dic['safe'], # Safe search 834 | 'k1': '-1', # Advertisements off 835 | 'vqd': dic['vqd'], # vqd string from button 836 | }, 837 | proxies=self._proxies, 838 | expected_code=200) 839 | except Exception as e: 840 | LOGERR(e) 841 | return None 842 | 843 | return r 844 | 845 | 846 | def annotate_tag(annotated_starttag_handler): 847 | # See parser logic within the DdgParser class for documentation. 848 | # 849 | # annotated_starttag_handler(self, tag: str, attrsdict: dict) -> annotation 850 | # Returns: HTMLParser.handle_starttag(self, tag: str, attrs: list) -> None 851 | 852 | def handler(self, tag, attrs): 853 | attrs = dict(attrs) 854 | annotation = annotated_starttag_handler(self, tag, attrs) 855 | self.insert_annotation(tag, annotation) 856 | 857 | return handler 858 | 859 | 860 | def retrieve_tag_annotation(annotated_endtag_handler): 861 | # See parser logic within the DdgParser class for documentation. 862 | # 863 | # annotated_endtag_handler(self, tag: str, annotation) -> None 864 | # Returns: HTMLParser.handle_endtag(self, tag: str) -> None 865 | 866 | def handler(self, tag): 867 | try: 868 | annotation = self.tag_annotations[tag].pop() 869 | except IndexError: 870 | # Malformed HTML -- more close tags than open tags 871 | annotation = None 872 | annotated_endtag_handler(self, tag, annotation) 873 | 874 | return handler 875 | 876 | 877 | class DdgParser(html.parser.HTMLParser): 878 | """The members of this class parse the result HTML 879 | page fetched from DuckDuckGo server for a query. 880 | 881 | The custom parser looks for tags enclosing search 882 | results and extracts the URL, title and text for 883 | each search result. 884 | 885 | After parsing the complete HTML page results are 886 | returned in a list of objects of class Result. 887 | """ 888 | 889 | # Parser logic: 890 | # 891 | # - Guiding principles: 892 | # 893 | # 1. Tag handlers are contextual; 894 | # 895 | # 2. Contextual starttag and endtag handlers should come in pairs 896 | # and have a clear hierarchy; 897 | # 898 | # 3. starttag handlers should only yield control to a pair of 899 | # child handlers (that is, one level down the hierarchy), and 900 | # correspondingly, endtag handlers should only return control 901 | # to the parent (that is, the pair of handlers that gave it 902 | # control in the first place). 903 | # 904 | # Principle 3 is meant to enforce a (possibly implicit) stack 905 | # structure and thus prevent careless jumps that result in what's 906 | # essentially spaghetti code with liberal use of GOTOs. 907 | # 908 | # - HTMLParser.handle_endtag gives us a bare tag name without 909 | # context, which is not good for enforcing principle 3 when we 910 | # have, say, nested div tags. 911 | # 912 | # In order to precisely identify the matching opening tag, we 913 | # maintain a stack for each tag name with *annotations*. Important 914 | # opening tags (e.g., the ones where child handlers are 915 | # registered) can be annotated so that when we can watch for the 916 | # annotation in the endtag handler, and when the appropriate 917 | # annotation is popped, we perform the corresponding action (e.g., 918 | # switch back to old handlers). 919 | # 920 | # To facilitate this, each starttag handler is decorated with 921 | # @annotate_tag, which accepts a return value that is the 922 | # annotation (None by default), and additionally converts attrs to 923 | # a dict, which is much easier to work with; and each endtag 924 | # handler is decorated with @retrieve_tag_annotation which sends 925 | # an additional parameter that is the retrieved annotation to the 926 | # handler. 927 | # 928 | # Note that some of our tag annotation stacks leak over time: this 929 | # happens to tags like and
which are not 930 | # closed. However, these tags play no structural role, and come 931 | # only in small quantities, so it's not really a problem. 932 | # 933 | # - All textual data (result title, result abstract, etc.) are 934 | # processed through a set of shared handlers. These handlers store 935 | # text in a shared buffer self.textbuf which can be retrieved and 936 | # cleared at appropriate times. 937 | # 938 | # Data (including charrefs and entityrefs) are ignored initially, 939 | # and when data needs to be recorded, the start_populating_textbuf 940 | # method is called to register the appropriate data, charref and 941 | # entityref handlers so that they append to self.textbuf. When 942 | # recording ends, pop_textbuf should be called to extract the text 943 | # and clear the buffer. stop_populating_textbuf returns the 944 | # handlers to their pristine state (ignoring data). 945 | # 946 | # Methods: 947 | # - start_populating_textbuf(self, data_transformer: Callable[[str], str]) -> None 948 | # - pop_textbuf(self) -> str 949 | # - stop_populating_textbuf(self) -> None 950 | # 951 | # - Outermost starttag and endtag handler methods: root_*. The whole 952 | # parser starts and ends in this state. 953 | # 954 | # - Each result is wrapped in a
tag with class "links_main". 955 | # 956 | # 957 | # 959 | # 960 | # - For each result, the first

tag with class "result__title" contains the 961 | # hyperlinked title. 962 | # 963 | # 964 | #

965 | #

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

tag. 969 | # 970 | # 971 | # 972 | # 973 | # 974 | # - Each title looks like 975 | # 976 | #

977 | # 978 | # 980 | # result title 981 | # 983 | # file type (e.g. [PDF]) 984 | # 986 | # 988 | #

989 | 990 | def __init__(self, offset=0): 991 | html.parser.HTMLParser.__init__(self) 992 | 993 | self.title = '' 994 | self.url = '' 995 | self.abstract = '' 996 | self.filetype = '' 997 | 998 | self.results = [] 999 | self.index = offset 1000 | self.textbuf = '' 1001 | self.click_result = '' 1002 | self.tag_annotations = {} 1003 | self.np_prev_button = '' 1004 | self.np_next_button = '' 1005 | self.npfound = False # First next params found 1006 | self.set_handlers_to('root') 1007 | self.vqd = '' # vqd returned from button, required for search query to get next set of results 1008 | 1009 | # Tag handlers 1010 | 1011 | @annotate_tag 1012 | def root_start(self, tag, attrs): 1013 | if tag == 'div': 1014 | if 'zci__result' in self.classes(attrs): 1015 | self.start_populating_textbuf() 1016 | return 'click_result' 1017 | 1018 | if 'links_main' in self.classes(attrs): 1019 | # Initialize result field registers 1020 | self.title = '' 1021 | self.url = '' 1022 | self.abstract = '' 1023 | self.filetype = '' 1024 | 1025 | self.set_handlers_to('result') 1026 | return 'result' 1027 | 1028 | if 'nav-link' in self.classes(attrs): 1029 | self.set_handlers_to('input') 1030 | return 'input' 1031 | return '' 1032 | 1033 | @retrieve_tag_annotation 1034 | def root_end(self, tag, annotation): 1035 | if annotation == 'click_result': 1036 | self.stop_populating_textbuf() 1037 | self.click_result = self.pop_textbuf() 1038 | self.set_handlers_to('root') 1039 | 1040 | @annotate_tag 1041 | def result_start(self, tag, attrs): 1042 | if tag == 'h2' and 'result__title' in self.classes(attrs): 1043 | self.set_handlers_to('title') 1044 | return 'title' 1045 | 1046 | if tag == 'a' and 'result__snippet' in self.classes(attrs) and 'href' in attrs: 1047 | self.start_populating_textbuf() 1048 | return 'abstract' 1049 | 1050 | return '' 1051 | 1052 | @retrieve_tag_annotation 1053 | def result_end(self, tag, annotation): 1054 | if annotation == 'abstract': 1055 | self.stop_populating_textbuf() 1056 | self.abstract = self.pop_textbuf() 1057 | elif annotation == 'result': 1058 | if self.url: 1059 | self.index += 1 1060 | result = Result(self.index, self.title, self.url, self.abstract, None) 1061 | self.results.append(result) 1062 | self.set_handlers_to('root') 1063 | 1064 | @annotate_tag 1065 | def title_start(self, tag, attrs): 1066 | if tag == 'span': 1067 | # Print a space after the filetype indicator 1068 | self.start_populating_textbuf(lambda text: '[' + text + ']') 1069 | return 'title_filetype' 1070 | 1071 | if tag == 'a' and 'href' in attrs: 1072 | # Skip 'News for', 'Images for' search links 1073 | if attrs['href'].startswith('/search'): 1074 | return '' 1075 | 1076 | self.url = attrs['href'] 1077 | try: 1078 | start = self.url.index('?q=') + len('?q=') 1079 | end = self.url.index('&sa=', start) 1080 | self.url = urllib.parse.unquote_plus(self.url[start:end]) 1081 | except ValueError: 1082 | pass 1083 | self.start_populating_textbuf() 1084 | return 'title_link' 1085 | 1086 | return '' 1087 | 1088 | @retrieve_tag_annotation 1089 | def title_end(self, tag, annotation): 1090 | if annotation == 'title_filetype': 1091 | self.stop_populating_textbuf() 1092 | self.filetype = self.pop_textbuf() 1093 | self.start_populating_textbuf() 1094 | elif annotation == 'title_link': 1095 | self.stop_populating_textbuf() 1096 | self.title = self.pop_textbuf() 1097 | if self.filetype != '': 1098 | self.title = self.filetype + self.title 1099 | elif annotation == 'title': 1100 | self.set_handlers_to('result') 1101 | 1102 | @annotate_tag 1103 | def abstract_start(self, tag, attrs): 1104 | if tag == 'span' and 'st' in self.classes(attrs): 1105 | self.start_populating_textbuf() 1106 | return 'abstract_text' 1107 | return '' 1108 | 1109 | @retrieve_tag_annotation 1110 | def abstract_end(self, tag, annotation): 1111 | if annotation == 'abstract_text': 1112 | self.stop_populating_textbuf() 1113 | self.abstract = self.pop_textbuf() 1114 | elif annotation == 'abstract': 1115 | self.set_handlers_to('result') 1116 | 1117 | @annotate_tag 1118 | def input_start(self, tag, attrs): 1119 | if tag == 'input' and 'name' in attrs: 1120 | if attrs['name'] == 'nextParams': 1121 | # The previous button always shows before next button 1122 | # If there's only 1 button (page 1), it's the next button 1123 | if self.npfound is True: 1124 | self.np_prev_button = self.np_next_button 1125 | else: 1126 | self.npfound = True 1127 | 1128 | self.np_next_button = attrs['value'] 1129 | return 1130 | if attrs['name'] == 'vqd' and attrs['value'] != '': 1131 | # vqd required to be passed for next/previous search page 1132 | self.vqd = attrs['value'] 1133 | return 1134 | 1135 | @retrieve_tag_annotation 1136 | def input_end(self, tag, annotation): 1137 | return 1138 | 1139 | # Generic methods 1140 | 1141 | # Set handle_starttag to SCOPE_start, and handle_endtag to SCOPE_end. 1142 | def set_handlers_to(self, scope): 1143 | self.handle_starttag = getattr(self, scope + '_start') 1144 | self.handle_endtag = getattr(self, scope + '_end') 1145 | 1146 | def insert_annotation(self, tag, annotation): 1147 | if tag not in self.tag_annotations: 1148 | self.tag_annotations[tag] = [] 1149 | self.tag_annotations[tag].append(annotation) 1150 | 1151 | def start_populating_textbuf(self, data_transformer=None): 1152 | if data_transformer is None: 1153 | # Record data verbatim 1154 | self.handle_data = self.record_data 1155 | else: 1156 | def record_transformed_data(data): 1157 | self.textbuf += data_transformer(data) 1158 | 1159 | self.handle_data = record_transformed_data 1160 | 1161 | self.handle_entityref = self.record_entityref 1162 | self.handle_charref = self.record_charref 1163 | 1164 | def pop_textbuf(self): 1165 | text = self.textbuf 1166 | self.textbuf = '' 1167 | return text 1168 | 1169 | def stop_populating_textbuf(self): 1170 | self.handle_data = lambda data: None 1171 | self.handle_entityref = lambda ref: None 1172 | self.handle_charref = lambda ref: None 1173 | 1174 | def record_data(self, data): 1175 | self.textbuf += data 1176 | 1177 | def record_entityref(self, ref): 1178 | try: 1179 | self.textbuf += chr(html.entities.name2codepoint[ref]) 1180 | except KeyError: 1181 | # Entity name not found; most likely rather sloppy HTML 1182 | # where a literal ampersand is not escaped; For instance, 1183 | # containing the following tag 1184 | # 1185 | #

expected market return s&p 500

1186 | # 1187 | # where &p is interpreted by HTMLParser as an entity (this 1188 | # behaviour seems to be specific to Python 2.7). 1189 | self.textbuf += '&' + ref 1190 | 1191 | def record_charref(self, ref): 1192 | if ref.startswith('x'): 1193 | char = chr(int(ref[1:], 16)) 1194 | else: 1195 | char = chr(int(ref)) 1196 | self.textbuf += char 1197 | 1198 | @staticmethod 1199 | def classes(attrs): 1200 | """Get tag's classes from its attribute dict.""" 1201 | return attrs.get('class', '').split() 1202 | 1203 | def error(self, message): 1204 | raise NotImplementedError("subclasses of ParserBase must override error()") 1205 | 1206 | 1207 | Colors = collections.namedtuple('Colors', 'index, title, url, metadata, abstract, prompt, reset') 1208 | 1209 | 1210 | class Result: 1211 | """ 1212 | Container for one search result, with output helpers. 1213 | 1214 | Parameters 1215 | ---------- 1216 | index : int or str 1217 | title : str 1218 | url : str 1219 | abstract : str 1220 | metadata : str, optional 1221 | Only applicable to DuckDuckGo News results, with publisher name and 1222 | publishing time. 1223 | 1224 | Attributes 1225 | ---------- 1226 | index : str 1227 | title : str 1228 | url : str 1229 | abstract : str 1230 | metadata : str or None 1231 | 1232 | Class Variables 1233 | --------------- 1234 | colors : str 1235 | 1236 | Methods 1237 | ------- 1238 | print() 1239 | jsonizable_object() 1240 | urltable() 1241 | 1242 | """ 1243 | 1244 | # Class variables 1245 | colors = None 1246 | urlexpand = False 1247 | 1248 | def __init__(self, index, title, url, abstract, metadata=None): 1249 | index = str(index) 1250 | self.index = index 1251 | self.title = title 1252 | self.url = url 1253 | self.abstract = abstract 1254 | self.metadata = metadata 1255 | 1256 | self._urltable = {index: url} 1257 | 1258 | def _print_title_and_url(self, index, title, url): 1259 | indent = INDENT - 2 1260 | colors = self.colors 1261 | 1262 | if not self.urlexpand: 1263 | url = '[' + urllib.parse.urlparse(url).netloc + ']' 1264 | 1265 | if colors: 1266 | # Adjust index to print result index clearly 1267 | print(" %s%-*s%s" % (colors.index, indent, index + '.', colors.reset), end='') 1268 | if not self.urlexpand: 1269 | print(' ' + colors.title + title + colors.reset + ' ' + colors.url + url + colors.reset) 1270 | else: 1271 | print(' ' + colors.title + title + colors.reset) 1272 | print(' ' * (INDENT) + colors.url + url + colors.reset) 1273 | else: 1274 | if self.urlexpand: 1275 | print(' %-*s %s' % (indent, index + '.', title)) 1276 | print(' %s%s' % (' ' * (indent + 1), url)) 1277 | else: 1278 | print(' %-*s %s %s' % (indent, index + '.', title, url)) 1279 | 1280 | def _print_metadata_and_abstract(self, abstract, metadata=None): 1281 | colors = self.colors 1282 | try: 1283 | columns, _ = os.get_terminal_size() 1284 | except OSError: 1285 | columns = 0 1286 | 1287 | if metadata: 1288 | if colors: 1289 | print(' ' * INDENT + colors.metadata + metadata + colors.reset) 1290 | else: 1291 | print(' ' * INDENT + metadata) 1292 | 1293 | if colors: 1294 | print(colors.abstract, end='') 1295 | if columns > INDENT + 1: 1296 | # Try to fill to columns 1297 | fillwidth = columns - INDENT - 1 1298 | for line in textwrap.wrap(abstract.replace('\n', ''), width=fillwidth): 1299 | print('%s%s' % (' ' * INDENT, line)) 1300 | print('') 1301 | else: 1302 | print('%s\n' % abstract.replace('\n', ' ')) 1303 | if colors: 1304 | print(colors.reset, end='') 1305 | 1306 | def print(self): 1307 | """Print the result entry.""" 1308 | 1309 | self._print_title_and_url(self.index, self.title, self.url) 1310 | self._print_metadata_and_abstract(self.abstract, metadata=self.metadata) 1311 | 1312 | def print_paginated(self, display_index): 1313 | """Print the result entry with custom index.""" 1314 | 1315 | self._print_title_and_url(display_index, self.title, self.url) 1316 | self._print_metadata_and_abstract(self.abstract, metadata=self.metadata) 1317 | 1318 | def jsonizable_object(self): 1319 | """Return a JSON-serializable dict representing the result entry.""" 1320 | obj = { 1321 | 'title': self.title, 1322 | 'url': self.url, 1323 | 'abstract': self.abstract 1324 | } 1325 | if self.metadata: 1326 | obj['metadata'] = self.metadata 1327 | return obj 1328 | 1329 | def urltable(self): 1330 | """Return a index-to-URL table for the current result. 1331 | 1332 | Normally, the table contains only a single entry, but when the result 1333 | contains sitelinks, all sitelinks are included in this table. 1334 | 1335 | Returns 1336 | ------- 1337 | dict 1338 | A dict mapping indices (strs) to URLs (also strs). 1339 | 1340 | """ 1341 | return self._urltable 1342 | 1343 | 1344 | class DdgCmdException(Exception): 1345 | pass 1346 | 1347 | 1348 | class NoKeywordsException(DdgCmdException): 1349 | pass 1350 | 1351 | 1352 | def require_keywords(method): 1353 | # Require keywords to be set before we run a DdgCmd method. If 1354 | # no keywords have been set, raise a NoKeywordsException. 1355 | @functools.wraps(method) 1356 | def enforced_method(self, *args, **kwargs): 1357 | if not self.keywords: 1358 | raise NoKeywordsException('No keywords.') 1359 | method(self, *args, **kwargs) 1360 | 1361 | return enforced_method 1362 | 1363 | 1364 | def no_argument(method): 1365 | # Normalize a do_* method of DdgCmd that takes no argument to 1366 | # one that takes an arg, but issue a warning when an nonempty 1367 | # argument is given. 1368 | @functools.wraps(method) 1369 | def enforced_method(self, arg): 1370 | if arg: 1371 | method_name = arg.__name__ 1372 | command_name = method_name[3:] if method_name.startswith('do_') else method_name 1373 | LOGGER.warning("Argument to the '%s' command ignored.", command_name) 1374 | method(self) 1375 | 1376 | return enforced_method 1377 | 1378 | 1379 | class DdgCmd: 1380 | """ 1381 | Command line interpreter and executor class for ddgr. 1382 | 1383 | Inspired by PSL cmd.Cmd. 1384 | 1385 | Parameters 1386 | ---------- 1387 | opts : argparse.Namespace 1388 | Options and/or arguments. 1389 | ua : str, optional 1390 | User agent 1391 | 1392 | Attributes 1393 | ---------- 1394 | options : argparse.Namespace 1395 | Options that are currently in effect. Read-only attribute. 1396 | keywords : str or list or strs 1397 | Current keywords. Read-only attribute 1398 | 1399 | Methods 1400 | ------- 1401 | fetch() 1402 | display_instant_answer(json_output=False) 1403 | display_results(prelude='\n', json_output=False) 1404 | fetch_and_display(prelude='\n', json_output=False) 1405 | read_next_command() 1406 | help() 1407 | cmdloop() 1408 | 1409 | """ 1410 | 1411 | def __init__(self, opts, ua): 1412 | super().__init__() 1413 | self.cmd = '' 1414 | self.index = 0 1415 | self._opts = opts 1416 | 1417 | self._ddg_url = DdgUrl(opts) 1418 | proxy = opts.proxy if hasattr(opts, 'proxy') else None 1419 | self._conn = DdgConnection(proxy=proxy, ua=ua) 1420 | 1421 | self.results = [] 1422 | self.instant_answer = '' 1423 | self._urltable = {} 1424 | 1425 | colors = self.colors 1426 | message = 'ddgr (? for help)' 1427 | self.prompt = ((colors.prompt + message + colors.reset + ' ') 1428 | if (colors and os.getenv('DISABLE_PROMPT_COLOR') is None) else (message + ': ')) 1429 | 1430 | @property 1431 | def options(self): 1432 | """Current options.""" 1433 | return self._opts 1434 | 1435 | @property 1436 | def keywords(self): 1437 | """Current keywords.""" 1438 | return self._ddg_url.keywords 1439 | 1440 | @require_keywords 1441 | def fetch(self): 1442 | """Fetch a page and parse for results. 1443 | 1444 | Results are stored in ``self.results``. 1445 | Instant answer is stored in ``self.instant_answer``. 1446 | 1447 | Raises 1448 | ------ 1449 | DDGConnectionError 1450 | 1451 | See Also 1452 | -------- 1453 | fetch_and_display 1454 | 1455 | """ 1456 | # This method also sets self._urltable. 1457 | page = self._conn.fetch_page(self._ddg_url) 1458 | 1459 | if page is None: 1460 | return 1461 | 1462 | if LOGGER.isEnabledFor(logging.DEBUG): 1463 | fd, tmpfile = tempfile.mkstemp(prefix='ddgr-response-') 1464 | os.close(fd) 1465 | with open(tmpfile, 'w', encoding='utf-8') as fp: 1466 | fp.write(page) 1467 | LOGDBG("Response body written to '%s'.", tmpfile) 1468 | 1469 | if self._opts.num: 1470 | _index = len(self._urltable) 1471 | else: 1472 | _index = 0 1473 | self._urltable = {} 1474 | 1475 | parser = DdgParser(offset=_index) 1476 | parser.feed(page) 1477 | 1478 | if self._opts.num: 1479 | self.results.extend(parser.results) 1480 | else: 1481 | self.results = parser.results 1482 | 1483 | for r in parser.results: 1484 | self._urltable.update(r.urltable()) 1485 | 1486 | self._ddg_url.np_prev = parser.np_prev_button 1487 | self._ddg_url.np_next = parser.np_next_button 1488 | self._ddg_url.vqd = parser.vqd 1489 | 1490 | if parser.click_result: 1491 | self.instant_answer = parser.click_result.strip() 1492 | else: 1493 | self.instant_answer = '' 1494 | 1495 | self._ddg_url.update_num(len(parser.results)) 1496 | 1497 | @require_keywords 1498 | def display_instant_answer(self, json_output=False): 1499 | """Display instant answer stored in ``self.instant_answer``. 1500 | 1501 | Parameters 1502 | ---------- 1503 | json_output : bool, optional 1504 | Whether to dump results in JSON format. Default is False. 1505 | 1506 | See Also 1507 | -------- 1508 | fetch_and_display 1509 | 1510 | """ 1511 | if self.index == 0 and self.instant_answer and not json_output: 1512 | if self.colors: 1513 | print(self.colors.abstract) 1514 | 1515 | try: 1516 | columns, _ = os.get_terminal_size() 1517 | except OSError: 1518 | columns = 0 1519 | 1520 | fillwidth = columns - INDENT 1521 | for line in textwrap.wrap(self.instant_answer, width=fillwidth): 1522 | print('%s%s' % (' ' * INDENT, line)) 1523 | 1524 | if self.colors: 1525 | print(self.colors.reset, end='') 1526 | 1527 | if self._opts.reverse or self._opts.instant: 1528 | print('') 1529 | 1530 | @require_keywords 1531 | def display_results(self, prelude='\n', json_output=False): 1532 | """Display results stored in ``self.results``. 1533 | 1534 | Parameters 1535 | ---------- 1536 | See `fetch_and_display`. 1537 | 1538 | """ 1539 | 1540 | if self._opts.num: 1541 | results = self.results[self.index:(self.index + self._opts.num)] 1542 | else: 1543 | results = self.results 1544 | 1545 | if self._opts.reverse: 1546 | results.reverse() 1547 | 1548 | if json_output: 1549 | # JSON output 1550 | results_object = [r.jsonizable_object() for r in results] 1551 | print(json.dumps(results_object, indent=2, sort_keys=True, ensure_ascii=False)) 1552 | elif not results: 1553 | print('No results.', file=sys.stderr) 1554 | else: 1555 | sys.stderr.write(prelude) 1556 | 1557 | if self._opts.num: # Paginated output 1558 | for i, r in enumerate(results): 1559 | if self._opts.reverse: 1560 | r.print_paginated(str(len(results) - i)) 1561 | else: 1562 | r.print_paginated(str(i + 1)) 1563 | else: # Regular output 1564 | for r in results: 1565 | r.print() 1566 | 1567 | @require_keywords 1568 | def fetch_and_display(self, prelude='\n', json_output=False): 1569 | """Fetch a page and display results. 1570 | 1571 | Results are stored in ``self.results``. 1572 | 1573 | Parameters 1574 | ---------- 1575 | prelude : str, optional 1576 | A string that is written to stderr before showing actual results, 1577 | usually serving as a separator. Default is an empty line. 1578 | json_output : bool, optional 1579 | Whether to dump results in JSON format. Default is False. 1580 | 1581 | Raises 1582 | ------ 1583 | DDGConnectionError 1584 | 1585 | See Also 1586 | -------- 1587 | fetch 1588 | display_instant_answer 1589 | display_results 1590 | 1591 | """ 1592 | self.fetch() 1593 | if not self._opts.reverse: 1594 | self.display_instant_answer() 1595 | self.display_results(prelude=prelude, json_output=json_output) 1596 | else: 1597 | self.display_results(prelude=prelude, json_output=json_output) 1598 | self.display_instant_answer() 1599 | 1600 | def read_next_command(self): 1601 | """Show omniprompt and read user command line. 1602 | 1603 | Command line is always stripped, and each consecutive group of 1604 | whitespace is replaced with a single space character. If the 1605 | command line is empty after stripping, when ignore it and keep 1606 | reading. Exit with status 0 if we get EOF or an empty line 1607 | (pre-strip, that is, a raw ) twice in a row. 1608 | 1609 | The new command line (non-empty) is stored in ``self.cmd``. 1610 | 1611 | """ 1612 | enter_count = 0 1613 | while True: 1614 | try: 1615 | cmd = input(self.prompt) 1616 | except EOFError: 1617 | sys.exit(0) 1618 | 1619 | if not cmd: 1620 | enter_count += 1 1621 | if enter_count == 2: 1622 | # Double 1623 | sys.exit(0) 1624 | else: 1625 | enter_count = 0 1626 | 1627 | cmd = ' '.join(cmd.split()) 1628 | if cmd: 1629 | self.cmd = cmd 1630 | break 1631 | 1632 | @staticmethod 1633 | def help(): 1634 | DdgArgumentParser.print_omniprompt_help(sys.stderr) 1635 | printerr('') 1636 | 1637 | @require_keywords 1638 | @no_argument 1639 | def do_first(self): 1640 | if self._opts.num: 1641 | if self.index < self._opts.num: 1642 | print('Already at the first page.', file=sys.stderr) 1643 | else: 1644 | self.index = 0 1645 | self.display_results() 1646 | return 1647 | 1648 | try: 1649 | self._ddg_url.first_page() 1650 | except ValueError as e: 1651 | print(e, file=sys.stderr) 1652 | return 1653 | 1654 | self.fetch_and_display() 1655 | 1656 | def do_ddg(self, arg): 1657 | if self._opts.num: 1658 | self.index = 0 1659 | self.results = [] 1660 | self._urltable = {} 1661 | # Update keywords and reconstruct URL 1662 | self._opts.keywords = arg 1663 | self._ddg_url = DdgUrl(self._opts) 1664 | # If there is a Bang, let DuckDuckGo do the work 1665 | if arg[0] == '!' or (len(arg) > 1 and arg[1] == '!'): 1666 | open_url(self._ddg_url.full()) 1667 | else: 1668 | self.fetch_and_display() 1669 | 1670 | @require_keywords 1671 | @no_argument 1672 | def do_next(self): 1673 | if self._opts.num: 1674 | count = len(self.results) 1675 | if self._ddg_url._qrycnt == 0 and self.index >= count: 1676 | print('No results.', file=sys.stderr) 1677 | return 1678 | 1679 | self.index += self._opts.num 1680 | if count - self.index < self._opts.num: 1681 | self._ddg_url.next_page() 1682 | self.fetch_and_display() 1683 | else: 1684 | self.display_results() 1685 | elif self._ddg_url._qrycnt == 0: 1686 | # If no results were fetched last time, we have hit the last page already 1687 | print('No results.', file=sys.stderr) 1688 | else: 1689 | self._ddg_url.next_page() 1690 | self.fetch_and_display() 1691 | 1692 | def handle_range(self, nav, low, high): 1693 | try: 1694 | if self._opts.num: 1695 | vals = [int(x) + self.index for x in nav.split('-')] 1696 | else: 1697 | vals = [int(x) for x in nav.split('-')] 1698 | 1699 | if len(vals) != 2: 1700 | printerr('Invalid range %s.' % nav) 1701 | return 1702 | 1703 | if vals[0] > vals[1]: 1704 | vals[0], vals[1] = vals[1], vals[0] 1705 | 1706 | for _id in range(vals[0], vals[1] + 1): 1707 | if self._opts.num and _id not in range(low, high): 1708 | printerr('Invalid index %s.' % (_id - self.index)) 1709 | continue 1710 | 1711 | if str(_id) in self._urltable: 1712 | open_url(self._urltable[str(_id)]) 1713 | else: 1714 | printerr('Invalid index %s.' % _id) 1715 | except ValueError: 1716 | printerr('Invalid range %s.' % nav) 1717 | 1718 | @require_keywords 1719 | def do_open(self, low, high, *args): 1720 | if not args: 1721 | printerr('Index or range missing.') 1722 | return 1723 | 1724 | for nav in args: 1725 | if nav == 'a': 1726 | for key, _ in sorted(self._urltable.items()): 1727 | if self._opts.num and int(key) not in range(low, high): 1728 | continue 1729 | open_url(self._urltable[key]) 1730 | elif nav in self._urltable: 1731 | if self._opts.num: 1732 | nav = str(int(nav) + self.index) 1733 | if int(nav) not in range(low, high): 1734 | printerr('Invalid index %s.' % (int(nav) - self.index)) 1735 | continue 1736 | open_url(self._urltable[nav]) 1737 | elif '-' in nav: 1738 | self.handle_range(nav, low, high) 1739 | else: 1740 | printerr('Invalid index %s.' % nav) 1741 | 1742 | @require_keywords 1743 | @no_argument 1744 | def do_previous(self): 1745 | if self._opts.num: 1746 | if self.index < self._opts.num: 1747 | print('Already at the first page.', file=sys.stderr) 1748 | else: 1749 | self.index -= self._opts.num 1750 | self.display_results() 1751 | return 1752 | 1753 | try: 1754 | self._ddg_url.prev_page() 1755 | except ValueError as e: 1756 | print(e, file=sys.stderr) 1757 | return 1758 | 1759 | self.fetch_and_display() 1760 | 1761 | def copy_url(self, idx): 1762 | try: 1763 | content = self._urltable[str(idx)].encode('utf-8') 1764 | 1765 | # try copying the url to clipboard using native utilities 1766 | copier_params = [] 1767 | if sys.platform.startswith(('linux', 'freebsd', 'openbsd')): 1768 | if os.getenv('WAYLAND_DISPLAY') is not None and shutil.which('wl-copy') is not None: 1769 | copier_params = ['wl-copy'] 1770 | elif shutil.which('xsel') is not None: 1771 | copier_params = ['xsel', '-b', '-i'] 1772 | elif shutil.which('xclip') is not None: 1773 | copier_params = ['xclip', '-selection', 'clipboard'] 1774 | # If we're using Termux (Android) use its 'termux-api' 1775 | # add-on to set device clipboard. 1776 | elif shutil.which('termux-clipboard-set') is not None: 1777 | copier_params = ['termux-clipboard-set'] 1778 | elif sys.platform == 'darwin': 1779 | copier_params = ['pbcopy'] 1780 | elif sys.platform == 'win32': 1781 | copier_params = ['clip'] 1782 | elif sys.platform.startswith('haiku'): 1783 | copier_params = ['clipboard', '-i'] 1784 | 1785 | if copier_params: 1786 | Popen(copier_params, stdin=PIPE, stdout=sys.stdout, stderr=DEVNULL).communicate(content) 1787 | return 1788 | 1789 | # If native clipboard utilities are absent, try to use terminal multiplexers 1790 | # tmux 1791 | if os.getenv('TMUX_PANE'): 1792 | copier_params = ['tmux', 'set-buffer'] 1793 | Popen(copier_params + [content], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL).communicate() 1794 | print('URL copied to tmux buffer.') 1795 | return 1796 | 1797 | # GNU Screen paste buffer 1798 | if os.getenv('STY'): 1799 | copier_params = ['screen', '-X', 'readbuf', '-e', 'utf8'] 1800 | tmpfd, tmppath = tempfile.mkstemp() 1801 | try: 1802 | with os.fdopen(tmpfd, 'wb') as fp: 1803 | fp.write(content) 1804 | copier_params.append(tmppath) 1805 | Popen(copier_params, stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL).communicate() 1806 | finally: 1807 | os.unlink(tmppath) 1808 | return 1809 | 1810 | printerr('failed to locate suitable clipboard utility') 1811 | except Exception as e: 1812 | raise NoKeywordsException from e 1813 | 1814 | def cmdloop(self): 1815 | """Run REPL.""" 1816 | if self.keywords: 1817 | if self.keywords[0][0] == '!' or ( 1818 | len(self.keywords[0]) > 1 and self.keywords[0][1] == '!' 1819 | ): 1820 | open_url(self._ddg_url.full()) 1821 | else: 1822 | self.fetch_and_display() 1823 | 1824 | while True: 1825 | self.read_next_command() 1826 | # Automatic dispatcher 1827 | # 1828 | # We can't write a dispatcher for now because that could 1829 | # change behaviour of the prompt. However, we have already 1830 | # laid a lot of ground work for the dispatcher, e.g., the 1831 | # `no_argument' decorator. 1832 | 1833 | _num = self._opts.num 1834 | try: 1835 | cmd = self.cmd 1836 | if cmd == 'f': 1837 | self.do_first('') 1838 | elif cmd.startswith('d '): 1839 | self.do_ddg(cmd[2:]) 1840 | elif cmd == 'n': 1841 | self.do_next('') 1842 | elif cmd.startswith('o '): 1843 | self.do_open(self.index + 1, self.index + self._opts.num + 1, *cmd[2:].split()) 1844 | elif cmd.startswith('O '): 1845 | open_url.override_text_browser = True 1846 | self.do_open(self.index + 1, self.index + self._opts.num + 1, *cmd[2:].split()) 1847 | open_url.override_text_browser = False 1848 | elif cmd == 'p': 1849 | self.do_previous('') 1850 | elif cmd == 'q': 1851 | break 1852 | elif cmd == '?': 1853 | self.help() 1854 | elif _num and cmd.isdigit() and int(cmd) in range(1, _num + 1): 1855 | open_url(self._urltable[str(int(cmd) + self.index)]) 1856 | elif _num == 0 and cmd in self._urltable: 1857 | open_url(self._urltable[cmd]) 1858 | elif self.keywords and cmd.isdigit() and int(cmd) < 100: 1859 | printerr('Index out of bound. To search for the number, use d.') 1860 | elif cmd == 'x': 1861 | Result.urlexpand = not Result.urlexpand 1862 | self.display_results() 1863 | elif cmd.startswith('c ') and cmd[2:].isdigit(): 1864 | idx = int(cmd[2:]) 1865 | if 0 < idx <= min(self._opts.num, len(self._urltable)): 1866 | self.copy_url(int(self.index) + idx) 1867 | else: 1868 | printerr("invalid index") 1869 | else: 1870 | self.do_ddg(cmd) 1871 | except KeyError: 1872 | printerr('Index out of bound. To search for the number, use d.') 1873 | except NoKeywordsException: 1874 | printerr('Initiate a query first.') 1875 | 1876 | 1877 | class DdgArgumentParser(argparse.ArgumentParser): 1878 | """Custom argument parser for ddgr.""" 1879 | 1880 | # Print omniprompt help 1881 | @staticmethod 1882 | def print_omniprompt_help(file=None): 1883 | file = sys.stderr if file is None else file 1884 | file.write(textwrap.dedent(""" 1885 | omniprompt keys: 1886 | n, p, f fetch the next, prev or first set of search results 1887 | index open the result corresponding to index in browser 1888 | o [index|range|a ...] open space-separated result indices, ranges or all 1889 | O [index|range|a ...] like key 'o', but try to open in a GUI browser 1890 | d keywords new DDG search for 'keywords' with original options 1891 | should be used to search omniprompt keys and indices 1892 | x toggle url expansion 1893 | c index copy url to clipboard 1894 | q, ^D, double Enter exit ddgr 1895 | ? show omniprompt help 1896 | * other inputs are considered as new search keywords 1897 | """)) 1898 | 1899 | # Print information on ddgr 1900 | @staticmethod 1901 | def print_general_info(file=None): 1902 | file = sys.stderr if file is None else file 1903 | file.write(textwrap.dedent(""" 1904 | Version %s 1905 | Copyright © 2016-2025 Arun Prakash Jana 1906 | License: GPLv3 1907 | Webpage: https://github.com/jarun/ddgr 1908 | """ % _VERSION_)) 1909 | 1910 | # Augment print_help to print more than synopsis and options 1911 | def print_help(self, file=None): 1912 | super().print_help(file) 1913 | self.print_omniprompt_help(file) 1914 | self.print_general_info(file) 1915 | 1916 | # Automatically print full help text on error 1917 | def error(self, message): 1918 | sys.stderr.write('%s: error: %s\n\n' % (self.prog, message)) 1919 | self.print_help(sys.stderr) 1920 | self.exit(2) 1921 | 1922 | # Type guards 1923 | @staticmethod 1924 | def positive_int(arg): 1925 | """Try to convert a string into a positive integer.""" 1926 | try: 1927 | n = int(arg) 1928 | assert n > 0 1929 | return n 1930 | except (ValueError, AssertionError) as e: 1931 | raise argparse.ArgumentTypeError('%s is not a positive integer' % arg) from e 1932 | 1933 | @staticmethod 1934 | def nonnegative_int(arg): 1935 | """Try to convert a string into a nonnegative integer <= 25.""" 1936 | try: 1937 | n = int(arg) 1938 | assert n >= 0 1939 | assert n <= 25 1940 | return n 1941 | except (ValueError, AssertionError) as e: 1942 | raise argparse.ArgumentTypeError('%s is not a non-negative integer <= 25' % arg) from e 1943 | 1944 | @staticmethod 1945 | def is_duration(arg): 1946 | """Check if a string is a valid duration accepted by DuckDuckGo. 1947 | 1948 | A valid duration is of the form dNUM, where d is a single letter h 1949 | (hour), d (day), w (week), m (month), or y (year), and NUM is a 1950 | non-negative integer. 1951 | """ 1952 | try: 1953 | if arg[0] not in ('h', 'd', 'w', 'm', 'y') or int(arg[1:]) < 0: 1954 | raise ValueError 1955 | except (TypeError, IndexError, ValueError) as e: 1956 | raise argparse.ArgumentTypeError('%s is not a valid duration' % arg) from e 1957 | return arg 1958 | 1959 | @staticmethod 1960 | def is_colorstr(arg): 1961 | """Check if a string is a valid color string.""" 1962 | try: 1963 | assert len(arg) == 6 1964 | for c in arg: 1965 | assert c in COLORMAP 1966 | except AssertionError as e: 1967 | raise argparse.ArgumentTypeError('%s is not a valid color string' % arg) from e 1968 | return arg 1969 | 1970 | 1971 | # Miscellaneous functions 1972 | 1973 | def python_version(): 1974 | return '%d.%d.%d' % sys.version_info[:3] 1975 | 1976 | 1977 | def get_colorize(colorize): 1978 | if colorize == 'always': 1979 | return True 1980 | 1981 | if colorize == 'auto': 1982 | return sys.stdout.isatty() 1983 | 1984 | # colorize = 'never' 1985 | return False 1986 | 1987 | 1988 | def set_win_console_mode(): 1989 | # VT100 control sequences are supported on Windows 10 Anniversary Update and later. 1990 | # https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences 1991 | # https://docs.microsoft.com/en-us/windows/console/setconsolemode 1992 | if platform.release() == '10': 1993 | STD_OUTPUT_HANDLE = -11 1994 | STD_ERROR_HANDLE = -12 1995 | ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 1996 | try: 1997 | from ctypes import windll, wintypes, byref 1998 | kernel32 = windll.kernel32 1999 | for nhandle in (STD_OUTPUT_HANDLE, STD_ERROR_HANDLE): 2000 | handle = kernel32.GetStdHandle(nhandle) 2001 | old_mode = wintypes.DWORD() 2002 | if not kernel32.GetConsoleMode(handle, byref(old_mode)): 2003 | raise RuntimeError('GetConsoleMode failed') 2004 | new_mode = bin(old_mode.value) | ENABLE_VIRTUAL_TERMINAL_PROCESSING 2005 | if not kernel32.SetConsoleMode(handle, new_mode): 2006 | raise RuntimeError('SetConsoleMode failed') 2007 | # Note: No need to restore at exit. SetConsoleMode seems to 2008 | # be limited to the calling process. 2009 | except Exception: 2010 | pass 2011 | 2012 | 2013 | # Query autocompleter 2014 | 2015 | # This function is largely experimental and could raise any exception; 2016 | # you should be prepared to catch anything. When it works though, it 2017 | # returns a list of strings the prefix could autocomplete to (however, 2018 | # it is not guaranteed that they start with the specified prefix; for 2019 | # instance, they won't if the specified prefix ends in a punctuation 2020 | # mark.) 2021 | def completer_fetch_completions(prefix): 2022 | # One can pass the 'hl' query param to specify the language. We 2023 | # ignore that for now. 2024 | api_url = ('https://duckduckgo.com/ac/?q=%s&kl=wt-wt' % 2025 | urllib.parse.quote(prefix, safe='')) 2026 | # A timeout of 3 seconds seems to be overly generous already. 2027 | with urllib.request.urlopen(api_url, timeout=3) as resp: 2028 | resptxt = resp.read().decode('utf-8') 2029 | respobj = json.loads(resptxt) 2030 | return [entry['phrase'] for entry in respobj] 2031 | 2032 | 2033 | def completer_run(prefix): 2034 | if prefix: 2035 | completions = completer_fetch_completions('+'.join(prefix.split())) 2036 | if completions: 2037 | print('\n'.join(completions)) 2038 | sys.exit(0) 2039 | 2040 | 2041 | def parse_args(args=None, namespace=None): 2042 | """Parse ddgr arguments/options. 2043 | 2044 | Parameters 2045 | ---------- 2046 | args : list, optional 2047 | Arguments to parse. Default is ``sys.argv``. 2048 | namespace : argparse.Namespace 2049 | Namespace to write to. Default is a new namespace. 2050 | 2051 | Returns 2052 | ------- 2053 | argparse.Namespace 2054 | Namespace with parsed arguments / options. 2055 | 2056 | """ 2057 | 2058 | colorstr_env = os.getenv('DDGR_COLORS') 2059 | 2060 | argparser = DdgArgumentParser(description='DuckDuckGo from the terminal.') 2061 | addarg = argparser.add_argument 2062 | addarg('-n', '--num', type=argparser.nonnegative_int, default=10, metavar='N', 2063 | help='show N (0<=N<=25) results per page (default 10); N=0 shows actual number of results fetched per page') 2064 | addarg('-r', '--reg', dest='region', default='us-en', metavar='REG', 2065 | help="region-specific search e.g. 'us-en' for US (default); visit https://duckduckgo.com/params") 2066 | addarg('--colorize', nargs='?', choices=['auto', 'always', 'never'], 2067 | const='always', default='auto', 2068 | help="""whether to colorize output; defaults to 'auto', which enables 2069 | color when stdout is a tty device; using --colorize without an argument 2070 | is equivalent to --colorize=always""") 2071 | addarg('-C', '--nocolor', action='store_true', help='equivalent to --colorize=never') 2072 | addarg('--colors', dest='colorstr', type=argparser.is_colorstr, default=colorstr_env if colorstr_env else 'oCdgxy', metavar='COLORS', 2073 | help='set output colors (see man page for details)') 2074 | addarg('-j', '--ducky', action='store_true', help='open the first result in a web browser; implies --np') 2075 | addarg('-i', '--instant', action='store_true', help='show only the instant answer') 2076 | addarg('-t', '--time', dest='duration', metavar='SPAN', default='', choices=('d', 'w', 'm', 'y'), help='time limit search ' 2077 | '[d (1 day), w (1 wk), m (1 month), y (1 year)]') 2078 | addarg('-w', '--site', dest='sites', action='append', metavar='SITE', help='search sites using DuckDuckGo') 2079 | addarg('-x', '--expand', action='store_true', help='Show complete url in search results') 2080 | addarg('-p', '--proxy', metavar='URI', help='tunnel traffic through an HTTPS proxy; URI format: [http[s]://][user:pwd@]host[:port]') 2081 | addarg('--unsafe', action='store_true', help='disable safe search') 2082 | addarg('--noua', action='store_true', help='disable user agent') 2083 | addarg('--json', action='store_true', help='output in JSON format; implies --np') 2084 | addarg('--gb', '--gui-browser', dest='gui_browser', action='store_true', help='open a bang directly in gui browser') 2085 | addarg('--np', '--noprompt', dest='noninteractive', action='store_true', help='perform search and exit, do not prompt') 2086 | addarg('--rev', '--reverse', dest='reverse', action='store_true', help='list entries in reversed order') 2087 | addarg('--url-handler', metavar='UTIL', help='custom script or cli utility to open results') 2088 | addarg('--show-browser-logs', action='store_true', help='do not suppress browser output (stdout and stderr)') 2089 | addarg('-v', '--version', action='version', version=_VERSION_) 2090 | addarg('-d', '--debug', action='store_true', help='enable debugging') 2091 | addarg('keywords', nargs='*', metavar='KEYWORD', help='search keywords') 2092 | addarg('--complete', help=argparse.SUPPRESS) 2093 | 2094 | parsed = argparser.parse_args(args, namespace) 2095 | if parsed.nocolor: 2096 | parsed.colorize = 'never' 2097 | 2098 | return parsed 2099 | 2100 | 2101 | def main(): 2102 | opts = parse_args() 2103 | 2104 | # Set logging level 2105 | if opts.debug: 2106 | LOGGER.setLevel(logging.DEBUG) 2107 | LOGDBG('ddgr version %s Python version %s', _VERSION_, python_version()) 2108 | 2109 | # Handle query completer 2110 | if opts.complete is not None: 2111 | completer_run(opts.complete) 2112 | 2113 | check_stdout_encoding() 2114 | 2115 | # Add cmdline args to readline history 2116 | if opts.keywords: 2117 | try: 2118 | readline.add_history(' '.join(opts.keywords)) 2119 | except Exception: 2120 | pass 2121 | 2122 | # Set colors 2123 | colorize = get_colorize(opts.colorize) 2124 | 2125 | colors = Colors(*[COLORMAP[c] for c in opts.colorstr], reset=COLORMAP['x']) if colorize else None 2126 | Result.colors = colors 2127 | Result.urlexpand = opts.expand 2128 | DdgCmd.colors = colors 2129 | 2130 | # Try to enable ANSI color support in cmd or PowerShell on Windows 10 2131 | if sys.platform == 'win32' and sys.stdout.isatty() and colorize: 2132 | set_win_console_mode() 2133 | 2134 | if opts.url_handler is not None: 2135 | open_url.url_handler = opts.url_handler 2136 | else: 2137 | open_url.override_text_browser = bool(opts.gui_browser) 2138 | 2139 | # Handle browser output suppression 2140 | open_url.suppress_browser_output = not (opts.show_browser_logs or (os.getenv('BROWSER') in TEXT_BROWSERS)) 2141 | 2142 | try: 2143 | repl = DdgCmd(opts, '' if opts.noua else USER_AGENT) 2144 | 2145 | if opts.json or opts.ducky or opts.noninteractive or opts.instant: 2146 | # Non-interactive mode 2147 | if repl.keywords and ( 2148 | repl.keywords[0][0] == '!' or 2149 | (len(repl.keywords[0]) > 1 and repl.keywords[0][1] == '!') 2150 | ): 2151 | # Handle bangs 2152 | open_url(repl._ddg_url.full()) 2153 | else: 2154 | repl.fetch() 2155 | if opts.ducky: 2156 | if repl.results: 2157 | open_url(repl.results[0].url) 2158 | else: 2159 | print('No results.', file=sys.stderr) 2160 | elif opts.instant: 2161 | repl.display_instant_answer(json_output=opts.json) 2162 | else: 2163 | if not opts.reverse: 2164 | repl.display_instant_answer(json_output=opts.json) 2165 | repl.display_results(prelude='', json_output=opts.json) 2166 | else: 2167 | repl.display_results(prelude='', json_output=opts.json) 2168 | repl.display_instant_answer(json_output=opts.json) 2169 | 2170 | sys.exit(0) 2171 | 2172 | # Interactive mode 2173 | repl.cmdloop() 2174 | except Exception as e: 2175 | # If debugging mode is enabled, let the exception through for a traceback; 2176 | # otherwise, only print the exception error message. 2177 | if LOGGER.isEnabledFor(logging.DEBUG): 2178 | raise 2179 | 2180 | LOGERR(e) 2181 | sys.exit(1) 2182 | 2183 | 2184 | if __name__ == '__main__': 2185 | main() 2186 | --------------------------------------------------------------------------------