Compare commits

..

7 Commits

Author SHA1 Message Date
David Adam
1e68508b0c Authenticate connections to web_config service
- Require all requests to use a session path.
 - Use a redirect file to avoid exposing the URL on the command line, as
   it contains the session path.

Fix for CVE-2014-2914.
Closes #1438.
2014-08-07 18:53:31 +08:00
David Adam
2aac8e5dde Further fixes to universal variable server socket management
- Change fishd_path to std::string
- Warn, rather than exiting with an error, if the universal variable
  server path is not available, and provide more useful advice.
- Export the new __fishd_runtime_dir variable.
2014-08-07 18:53:16 +08:00
David Adam
209d8b7f2f Fix for CVE-2014-2905 - fishd restart required.
- Use a secure path for sockets (some code used under license from
   tmux).
 - Provide the secure path in the environment as $__fish_runtime_dir.
 - Link the new path to the old path to ease migration from earlier
   versions.

Closes #1359.

After installing fish built from or after this commit, you MUST
terminate all running fishd processes (`killall fishd`, `pkill fishd`
or similar). Distributors are encouraged to do this from within their
packaging scripts. fishd will restart automatically, and no data should
be lost.
2014-08-07 18:53:16 +08:00
David Adam
26663e042f Revert "Check effective credentials of socket peers"
This reverts commit aea9ad4965.

Just checking the credentials of the peer turns out to be
insufficient.
See https://github.com/fish-shell/fish-shell/issues/1436.
2014-08-07 18:52:27 +08:00
David Adam
55986120aa use mktemp(1) to generate temporary file names
Fix for CVE-2014-2906.

Closes a race condition in funced which would allow execution of
arbitrary code; closes a race condition in psub which would allow
alternation of the data stream.

Note that `psub -f` does not work (#1040); a fix should be committed
separately for ease of maintenance.
2014-04-27 12:23:24 +08:00
David Adam
aea9ad4965 Check effective credentials of socket peers
Fix for CVE-2014-2905.

Code for getpeereid() on non-BSD systems imported from the PostgreSQL
project under a BSD-style license.
2014-04-27 12:23:13 +08:00
Anders Bergh
216d32055d fish_config: Listen on both IPv6 and IPv4.
A subclass of TCPServer was created to deny any non-local connections and to
listen using an IPv6 socket.
2014-04-27 11:36:41 +08:00
887 changed files with 64864 additions and 298817 deletions

View File

@@ -1,8 +0,0 @@
# Use the Google style with these modifications:
#
# 1) lines can be up to 100 chars long rather than 80, and
# 2) use a four space indent rather than two spaces.
#
BasedOnStyle: Google
ColumnLimit: 100
IndentWidth: 4

25
.gitattributes vendored
View File

@@ -1,25 +1,4 @@
.gitattributes export-ignore .gitattributes export-ignore
.gitignore export-ignore .gitignore export-ignore
.travis.yml export-ignore /build_tools export-ignore
fish.spec.in export-ignore
/build_tools/make_svn_completions.fish export-ignore
/build_tools/description-pak export-ignore
/build_tools/make_hg_completions.fish export-ignore
/build_tools/make_vcs_completions.fish export-ignore
/build_tools/make_vcs_completions_generic.fish export-ignore
/build_tools/osx_package_resources export-ignore
/build_tools/osx_package_resources/terminal_logo.png export-ignore
/build_tools/osx_package_resources/welcome.rtf export-ignore
/build_tools/make_csv_completions.fish export-ignore
/build_tools/osx_distribution.xml export-ignore
/build_tools/make_tarball.sh export-ignore
/build_tools/make_deb.sh export-ignore
/build_tools/osx_package_scripts export-ignore
/build_tools/osx_package_scripts/add-shell export-ignore
/build_tools/osx_package_scripts/postinstall export-ignore
/build_tools/make_pkg.sh export-ignore
/build_tools/make_darcs_completions.fish export-ignore
/debian export-ignore
/debian/* export-ignore
/.github export-ignore
/.github/* export-ignore

View File

@@ -1,40 +0,0 @@
<!--
Thanks for helping to make fish better!
If you are asking for help with fish, or you've found a bug:
- Make sure it's not a known or solved issue, by searching https://github.com/fish-shell/fish-shell/issues
- Fill in the following information carefully:
-->
[Please include a short description of the problem here]
### Reproduction Steps:
1. [First Step]
2. [Second Step]
3. [Other Steps...]
### Expected behavior:
[Describe expected behavior here]
### Observed behavior:
[Describe observed behavior here]
### Additional information:
[ Other useful information, such as:
When did this problem start?
Does this happen all the time?
Has anything changed on your system recently?
]
---
Fish version: [from the output of fish --version]
Operating system: [your operating system and how you installed fish e.g. Homebrew, Ubuntu PPA, distribution package]
Terminal or terminal emulator: [e.g. PuTTy, iTerm2, GNOME Terminal, VT220]

25
.gitignore vendored
View File

@@ -1,43 +1,34 @@
*.o *.o
*~ *~
*.exe
*.xccheckout
.DS_Store Doxyfile.help
Makefile Makefile
autom4te.cache/ autom4te.cache/
build/ build/
command_list.txt command_list.txt
command_list_toc.txt
confdefs.h confdefs.h
config.h config.h
config.h.in config.h.in
config.log config.log
config.status config.status
configure configure
doc/
doc.h doc.h
doc_src/commands.hdr doc_src/commands.hdr
doc_src/index.hdr doc_src/index.hdr
po/*.gmo po/*.gmo
fish fish
fish.spec
fish_indent fish_indent
fish_pager
fish_tests fish_tests
fish.pc fishd
mimedb
seq seq
set_color set_color
share/__fish_build_paths.fish share/config.fish
share/man/ share/man/
toc.txt toc.txt
user_doc/ user_doc/
xcuserdata xcuserdata
test/ tests/*tmp.*
FISH-BUILD-VERSION-FILE tests/foo.txt
version
messages.pot
lexicon.txt
lexicon_filter
lexicon.log
DerivedData/
compile_commands.json
xcodebuild.log

View File

@@ -1,8 +0,0 @@
rules:
rule-configurations:
# This is the default value (as of the time I wrote this) but I'm making
# it explicit since it needs to agree with the value used by clang-format.
# Thus, if we ever change the fish style to allow longer lines this should
# be changed (as well as the corresponding clang-format config).
- key: LONG_LINE
value: 100

View File

@@ -1,63 +0,0 @@
language: cpp
sudo: false
matrix:
include:
- os: linux
compiler: gcc
addons:
apt:
packages:
- bc
- expect
- gettext
- libncurses5-dev
- os: linux
compiler: clang
addons:
apt:
sources:
- llvm-toolchain-precise-3.8
- ubuntu-toolchain-r-test
packages:
- clang-3.8
- llvm-3.8 # for llvm-symbolizer
- bc
- expect
- gettext
- libncurses5-dev
env:
- CXXFLAGS="-g -fno-omit-frame-pointer -fsanitize=address"
- ASAN_OPTIONS=check_initialization_order=1:detect_stack_use_after_return=1:detect_leaks=1
before_install: export CXX=clang++-3.8
- os: osx
before_install:
- brew update
- brew install pcre2 # use system PCRE2
fast_finish: true
script:
- autoreconf
- ./configure --prefix=$HOME/prefix || cat config.log
- make -j2
- make install
- make test DESTDIR=$HOME/prefix/ SHOW_INTERACTIVE_LOG=1
notifications:
# Some items are encrypted so that notifications from other repositories
# don't flood the official repositories.
irc:
channels:
#- "irc.oftc.net#fish"
secure: "eRk9KGZ5+mrlD2SoI8yg2Sp8OYrh7YPyGe3WCDQUwTnNgNDII34rbM9a6UOA/l7AeWSNY8joLq5xVLCU4wpFgUcJ11SYIpMnLosZK29OW4ubDOHmdBDvJ971rLgAVG9cXngZtIxEVVxN/jnS1Qr8GKZx4DjkaTMgz1pemb4WxCc="
template:
- "%{repository}#%{build_number} (%{commit} on %{branch} by %{author}): %{message} Details at %{build_url}"
use_notice: true
skip_join: true
webhooks:
urls:
#- https://webhooks.gitter.im/e/61821cec3015bf0f8bb1
secure: fPfOmxnC3MCsfR1oocVFeWLawGcRZkn+8fNHlSOeZ+SqqoZfcCHgQTvQ22TqmVl1yvkXbNlaXjo6dbVzTOAh7r7H0bRMEKBVh3dQS7wqjB1sKivpXd8PAS3BTj5MQpGeJzdHnDuwVlwDktGtfHfhGeq1Go/4IosOq8u+6RTe28g=

3
CHANGELOG Normal file
View File

@@ -0,0 +1,3 @@
24-01-2012 Jan Kanis
* Added a changelog file
* removed unescaping if the 'commandline' builtin is called without the -o (tokenise) flag

View File

@@ -1,401 +0,0 @@
# fish 2.3.0 (released May 20, 2016)
There are no significant changes between 2.3.0 and 2.3b2.
## Other notable fixes and improvements
- `abbr` now allows non-letter keys (#2996).
- Define a few extra colours on first start (#2987).
- Multiple documentation updates.
- Added completions for rmmod (#3007).
- Improved completions for git (#2998).
## Known issues
- Interactive commands started from fish configuration files or from the `-c` option may, under certain circumstances, be started with incorrect terminal modes and fail to behave as expected. A fix is planned but requires further testing (#2619).
---
# fish 2.3b2 (released May 5, 2016)
## Significant changes
- A new `fish_realpath` builtin and associated function to allow the use of `realpath` even on those platforms that don't ship an appropriate command (#2932).
- Alt-# toggles the current command line between commented and uncommented states, making it easy to save a command in history without executing it.
- The `fish_vi_mode` function is now deprecated in favour of `fish_vi_key_bindings`.
## Other notable fixes and improvements
- Fix the build on Cygwin (#2952) and RedHat Enterprise Linux/CentOS 5 (#2955).
- Avoid confusing the terminal line driver with non-printing characters in `fish_title` (#2453).
- Improved completions for busctl, git (#2585, #2879, #2984), and netctl.
---
# fish 2.3b1 (released April 19, 2016)
## Significant Changes
- A new `string` builtin to handle... strings! This builtin will measure, split, search and replace text strings, including using regular expressions. It can also be used to turn lists into plain strings using `join`. `string` can be used in place of `sed`, `grep`, `tr`, `cut`, and `awk` in many situations. (#2296)
- Allow using escape as the Meta modifier key, by waiting after seeing an escape character wait up to 300ms for an additional character. This is consistent with readline (e.g. bash) and can be configured via the `fish_escape_delay_ms variable`. This allows using escape as the Meta modifier. (#1356)
- Add new directories for vendor functions and configuration snippets (#2500)
- A new `fish_realpath` builtin and associated `realpath` function should allow scripts to resolve path names via `realpath` regardless of whether there is an external command of that name; albeit with some limitations. See the associated documentation.
## Backward-incompatible changes
- Unmatched globs will now cause an error, except when used with `for`, `set` or `count` (#2719)
- `and` and `or` will now bind to the closest `if` or `while`, allowing compound conditions without `begin` and `end` (#1428)
- `set -ql` now searches up to function scope for variables (#2502)
- `status -f` will now behave the same when run as the main script or using `source` (#2643)
- `source` no longer puts the file name in `$argv` if no arguments are given (#139)
- History files are stored under the `XDG_DATA_HOME` hierarchy (by default, in `~/.local/share`), and existing history will be moved on first use (#744)
## Other notable fixes and improvements
- Fish no longer silences errors in config.fish (#2702)
- Directory autosuggestions will now descend as far as possible if there is only one child directory (#2531)
- Add support for bright colors (#1464)
- Allow Ctrl-J (\cj) to be bound separately from Ctrl-M (\cm) (#217)
- psub now has a "-s"/"&#x2013;suffix" option to name the temporary file with that suffix
- Enable 24-bit colors on select terminals (#2495)
- Support for SVN status in the prompt (#2582)
- Mercurial and SVN support have been added to the Classic + Git (now Classic + VCS) prompt (via the new \__fish_vcs_prompt function) (#2592)
- export now handles variables with a "=" in the value (#2403)
- New completions for:
- alsactl
- Archlinux's asp, makepkg
- Atom's apm (#2390)
- entr - the "Event Notify Test Runner" (#2265)
- Fedora's dnf (#2638)
- OSX diskutil (#2738)
- pkgng (#2395)
- pulseaudio's pacmd and pactl
- rust's rustc and cargo (#2409)
- sysctl (#2214)
- systemd's machinectl (#2158), busctl (#2144), systemd-nspawn, systemd-analyze, localectl, timedatectl
- and more
- Fish no longer has a function called sgrep, freeing it for user customization (#2245)
- A rewrite of the completions for cd, fixing a few bugs (#2299, #2300, #562)
- Linux VTs now run in a simplified mode to avoid issues (#2311)
- The vi-bindings now inherit from the emacs bindings
- Fish will also execute `fish_user_key_bindings` when in vi-mode
- `funced` will now also check $VISUAL (#2268)
- A new `suspend` function (#2269)
- Subcommand completion now works better with split /usr (#2141)
- The command-not-found-handler can now be overridden by defining a function called `__fish_command_not_found_handler` in config.fish (#2332)
- A few fixes to the Sorin theme
- PWD shortening in the prompt can now be configured via the `fish_prompt_pwd_dir_length` variable, set to the length per path component (#2473)
- fish no longer requires `/etc/fish/config.fish` to correctly start, and now ships a skeleton file that only contains some documentation (#2799)
---
# fish 2.2.0 (released July 12, 2015)
### Significant changes ###
* Abbreviations: the new `abbr` command allows for interactively-expanded abbreviations, allowing quick access to frequently-used commands (#731).
* Vi mode: run `fish_vi_mode` to switch fish into the key bindings and prompt familiar to users of the Vi editor (#65).
* New inline and interactive pager, which will be familiar to users of zsh (#291).
* Underlying architectural changes: the `fishd` universal variable server has been removed as it was a source of many bugs and security problems. Notably, old fish sessions will not be able to communicate universal variable changes with new fish sessions. For best results, restart all running instances of `fish`.
* The web-based configuration tool has been redesigned, featuring a prompt theme chooser and other improvements.
* New German, Brazilian Portuguese, and Chinese translations.
### Backward-incompatible changes ###
These are kept to a minimum, but either change undocumented features or are too hard to use in their existing forms. These changes may break existing scripts.
* `commandline` no longer interprets functions "in reverse", instead behaving as expected (#1567).
* The previously-undocumented `CMD_DURATION` variable is now set for all commands and contains the execution time of the last command in milliseconds (#1585). It is no longer exported to other commands (#1896).
* `if` / `else` conditional statements now return values consistent with the Single Unix Specification, like other shells (#1443).
* A new "top-level" local scope has been added, allowing local variables declared on the commandline to be visible to subsequent commands. (#1908)
### Other notable fixes and improvements ###
* New documentation design (#1662), which requires a Doxygen version 1.8.7 or newer to build.
* Fish now defines a default directory for other packages to provide completions. By default this is `/usr/share/fish/vendor-completions.d`; on systems with `pkgconfig` installed this path is discoverable with `pkg-config --variable completionsdir fish`.
* A new parser removes many bugs; all existing syntax should keep working.
* New `fish_preexec` and `fish_postexec` events are fired before and after job execution respectively (#1549).
* Unmatched wildcards no longer prevent a job from running. Wildcards used interactively will still print an error, but the job will proceed and the wildcard will expand to zero arguments (#1482).
* The `.` command is deprecated and the `source` command is preferred (#310).
* `bind` supports "bind modes", which allows bindings to be set for a particular named mode, to support the implementation of Vi mode.
* A new `export` alias, which behaves like other shells (#1833).
* `command` has a new `--search` option to print the name of the disk file that would be executed, like other shells' `command -v` (#1540).
* `commandline` has a new `--paging-mode` option to support the new pager.
* `complete` has a new `--wraps` option, which allows a command to (recursively) inherit the completions of a wrapped command (#393), and `complete -e` now correctly erases completions (#380).
* Completions are now generated from manual pages by default on the first run of fish (#997).
* `fish_indent` can now produce colorized (`--ansi`) and HTML (`--html`) output (#1827).
* `functions --erase` now prevents autoloaded functions from being reloaded in the current session.
* `history` has a new `--merge` option, to incorporate history from other sessions into the current session (#825).
* `jobs` returns 1 if there are no active jobs (#1484).
* `read` has several new options:
* `--array` to break input into an array (#1540)
* `--null` to break lines on NUL characters rather than newlines (#1694)
* `--nchars` to read a specific number of characters (#1616)
* `--right-prompt` to display a right-hand-side prompt during interactive read (#1698).
* `type` has a new `-q` option to suppress output (#1540 and, like other shells, `type -a` now prints all matches for a command (#261).
* Pressing F1 now shows the manual page for the current command (#1063).
* `fish_title` functions have access to the arguments of the currently running argument as `$argv[1]` (#1542).
* The OS command-not-found handler is used on Arch Linux (#1925), nixOS (#1852), openSUSE and Fedora (#1280).
* `Alt`+`.` searches backwards in the token history, mapping to the same behavior as inserting the last argument of the previous command, like other shells (#89).
* The `SHLVL` environment variable is incremented correctly (#1634 & #1693).
* Added completions for `adb` (#1165 & #1211), `apt` (#2018), `aura` (#1292), `composer` (#1607), `cygport` (#1841), `dropbox` (#1533), `elixir` (#1167), `fossil`, `heroku` (#1790), `iex` (#1167), `kitchen` (#2000), `nix` (#1167), `node`/`npm` (#1566), `opam` (#1615), `setfacl` (#1752), `tmuxinator` (#1863), and `yast2` (#1739).
* Improved completions for `brew` (#1090 & #1810), `bundler` (#1779), `cd` (#1135), `emerge` (#1840),`git` (#1680, #1834 & #1951), `man` (#960), `modprobe` (#1124), `pacman` (#1292), `rpm` (#1236), `rsync` (#1872), `scp` (#1145), `ssh` (#1234), `sshfs` (#1268), `systemctl` (#1462, #1950 & #1972), `tmux` (#1853), `vagrant` (#1748), `yum` (#1269), and `zypper` (#1787).
---
# fish 2.1.2 (released Feb 24, 2015)
fish 2.1.2 contains a workaround for a filesystem bug in Mac OS X Yosemite. #1859
Specifically, after installing fish 2.1.1 and then rebooting, "Verify Disk" in Disk Utility will report "Invalid number of hard links." We don't have any reports of data loss or other adverse consequences. fish 2.1.2 avoids triggering the bug, but does not repair an already affected filesystem. To repair the filesystem, you can boot into Recovery Mode and use Repair Disk from Disk Utility. Linux and versions of OS X prior to Yosemite are believed to be unaffected.
There are no other changes in this release.
---
# fish 2.1.1 (released September 26, 2014)
__Important:__ if you are upgrading, stop all running instances of `fishd` as soon as possible after installing this release; it will be restarted automatically. On most systems, there will be no further action required. Note that some environments (where `XDG_RUNTIME_DIR` is set), such as Fedora 20, will require a restart of all running fish processes before universal variables work as intended.
Distributors are highly encouraged to call `killall fishd`, `pkill fishd` or similar in installation scripts, or to warn their users to do so.
### Security fixes
* The fish_config web interface now uses an authentication token to protect requests and only responds to requests from the local machine with this token, preventing a remote code execution attack. (closing CVE-2014-2914). #1438
* `psub` and `funced` are no longer vulnerable to attacks which allow local privilege escalation and data tampering (closing CVE-2014-2906 and CVE-2014-3856). #1437
* `fishd` uses a secure path for its socket, preventing a local privilege escalation attack (closing CVE-2014-2905). #1436
* `__fish_print_packages` is no longer vulnerable to attacks which would allow local privilege escalation and data tampering (closing CVE-2014-3219). #1440
### Other fixes
* `fishd` now ignores SIGPIPE, fixing crashes using tools like GNU Parallel and which occurred more often as a result of the other `fishd` changes. #1084 & #1690
---
# fish 2.1.0
Significant Changes
-------------------
* **Tab completions will fuzzy-match files.** #568
When tab-completing a file, fish will first attempt prefix matches (`foo` matches `foobar`), then substring matches (`ooba` matches `foobar`), and lastly subsequence matches (`fbr` matches `foobar`). For example, in a directory with files foo1.txt, foo2.txt, foo3.txt…, you can type only the numeric part and hit tab to fill in the rest.
This feature is implemented for files and executables. It is not yet implemented for options (like `--foobar`), and not yet implemented across path components (like `/u/l/b` to match `/usr/local/bin`).
* **Redirections now work better across pipelines.** #110, #877
In particular, you can pipe stderr and stdout together, for example, with `cmd ^&1 | tee log.txt`, or the more familiar `cmd 2>&1 | tee log.txt`.
* **A single `%` now expands to the last job backgrounded.** #1008
Previously, a single `%` would pid-expand to either all backgrounded jobs, or all jobs owned by your user. Now it expands to the last job backgrounded. If no job is in the background, it will fail to expand. In particular, `fg %` can be used to put the most recent background job in the foreground.
Other Notable Fixes
-------------------
* alt-U and alt+C now uppercase and capitalize words, respectively. #995
* VTE based terminals should now know the working directory. #906
* The autotools build now works on Mavericks. #968
* The end-of-line binding (ctrl+E) now accepts autosuggestions. #932
* Directories in `/etc/paths` (used on OS X) are now prepended instead of appended, similar to other shells. #927
* Option-right-arrow (used for partial autosuggestion completion) now works on iTerm2. #920
* Tab completions now work properly within nested subcommands. #913
* `printf` supports \e, the escape character. #910
* `fish_config history` no longer shows duplicate items. #900
* `$fish_user_paths` is now prepended to $PATH instead of appended. #888
* Jobs complete when all processes complete. #876
For example, in previous versions of fish, `sleep 10 | echo Done` returns control immediately, because echo does not read from stdin. Now it does not complete until sleep exits (presumably after 10 seconds).
* Better error reporting for square brackets. #875
* fish no longer tries to add `/bin` to `$PATH` unless PATH is totally empty. #852
* History token substitution (alt-up) now works correctly inside subshells. #833
* Flow control is now disabled, freeing up ctrl-S and ctrl-Q for other uses. #814
* sh-style variable setting like `foo=bar` now produces better error messages. #809
* Commands with wildcards no longer produce autosuggestions. #785
* funced no longer freaks out when supplied with no arguments. #780
* fish.app now works correctly in a directory containing spaces. #774
* Tab completion cycling no longer occasionally fails to repaint. #765
* Comments now work in eval'd strings. #684
* History search (up-arrow) now shows the item matching the autosuggestion, if that autosuggestion was truncated. #650
* Ctrl-T now transposes characters, as in other shells. #128
---
# fish 2.0.0
Significant Changes
-------------------
* **Command substitutions now modify `$status` #547.**
Previously the exit status of command substitutions (like `(pwd)`) was ignored; however now it modifies $status. Furthermore, the `set` command now only sets $status on failure; it is untouched on success. This allows for the following pattern:
```sh
if set python_path (which python)
...
end
```
Because set does not modify $status on success, the if branch effectively tests whether `which` succeeded, and if so, whether the `set` also succeeded.
* **Improvements to $PATH handling.**
* There is a new variable, `$fish_user_paths`, which can be set universally, and whose contents are appended to $PATH #527
* /etc/paths and /etc/paths.d are now respected on OS X
* fish no longer modifies $PATH to find its own binaries
* **Long lines no longer use ellipsis for line breaks**, and copy and paste
should no longer include a newline even if the line was broken #300
* **New syntax for index ranges** (sometimes known as "slices") #212
* **fish now supports an `else if` statement** #134
* **Process and pid completion now works on OS X** #129
* **fish is now relocatable**, and no longer depends on compiled-in paths #125
* **fish now supports a right prompt (RPROMPT)** through the fish_right_prompt function #80
* **fish now uses posix_spawn instead of fork when possible**, which is much faster on BSD and OS X #11
Other Notable Fixes
-------------------
* Updated VCS completions (darcs, cvs, svn, etc.)
* Avoid calling getcwd on the main thread, as it can hang #696
* Control-D (forward delete) no longer stops at a period #667
* Completions for many new commands
* fish now respects rxvt's unique keybindings #657
* xsel is no longer built as part of fish. It will still be invoked if installed separately #633
* __fish_filter_mime no longer spews #628
* The --no-execute option to fish no longer falls over when reaching the end of a block #624
* fish_config knows how to find fish even if it's not in the $PATH #621
* A leading space now prevents writing to history, as is done in bash and zsh #615
* Hitting enter after a backslash only goes to a new line if it is followed by whitespace or the end of the line #613
* printf is now a builtin #611
* Event handlers should no longer fire if signals are blocked #608
* set_color is now a builtin #578
* man page completions are now located in a new generated_completions directory, instead of your completions directory #576
* tab now clears autosuggestions #561
* tab completion from within a pair of quotes now attempts to "appropriate" the closing quote #552
* $EDITOR can now be a list: for example, `set EDITOR gvim -f`) #541
* `case` bodies are now indented #530
* The profile switch `-p` no longer crashes #517
* You can now control-C out of `read` #516
* `umask` is now functional on OS X #515
* Avoid calling getpwnam on the main thread, as it can hang #512
* Alt-F or Alt-right-arrow (Option-F or option-right-arrow) now accepts one word of an autosuggestion #435
* Setting fish as your login shell no longer kills OpenSUSE #367
* Backslashes now join lines, instead of creating multiple commands #347
* echo now implements the -e flag to interpret escapes #337
* When the last token in the user's input contains capital letters, use its case in preference to that of the autosuggestion #335
* Descriptions now have their own muted color #279
* Wildcards beginning with a . (for example, `ls .*`) no longer match . and .. #270
* Recursive wildcards now handle symlink loops #268
* You can now delete history items from the fish_config web interface #250
* The OS X build now weak links `wcsdup` and `wcscasecmp` #240
* fish now saves and restores the process group, which prevents certain processes from being erroneously reported as stopped #197
* funced now takes an editor option #187
* Alternating row colors are available in fish pager through `fish_pager_color_secondary` #186
* Universal variable values are now stored based on your MAC address, not your hostname #183
* The caret ^ now only does a stderr redirection if it is the first character of a token, making git users happy #168
* Autosuggestions will no longer cause line wrapping #167
* Better handling of Unicode combining characters #155
* fish SIGHUPs processes more often #138
* fish no longer causes `sudo` to ask for a password every time
* fish behaves better under Midnight Commander #121
* `set -e` no longer crashes #100
* fish now will automatically import history from bash, if there is no fish history #66
* Backslashed-newlines inside quoted strings now behave more intuitively #52
* Tab titles should be shown correctly in iTerm2 #47
* scp remote path completion now sometimes works #42
* The `read` builtin no longer shows autosuggestions #29
* Custom key bindings can now be set via the `fish_user_key_bindings` function #21
* All Python scripts now run correctly under both Python 2 and Python 3 #14
* The "accept autosuggestion" key can now be configured #19
* Autosuggestions will no longer suggest invalid commands #6
---
# fishfish Beta r2
Bug Fixes
---------
* **Implicit cd** is back, for paths that start with one or two dots, a slash, or a tilde.
* **Overrides of default functions should be fixed.** The "internalized scripts" feature is disabled for now.
* **Disabled delayed suspend.** This is a strange job-control feature of BSD systems, including OS X. Disabling it frees up Control Y for other purposes; in particular, for yank, which now works on OS X.
* **fish_indent is fixed.** In particular, the `funced` and `funcsave` functions work again.
* A SIGTERM now ends the whole execution stack again (resolving #13).
* Bumped the __fish_config_interactive version number so the default fish_color_autosuggestion kicks in.
* fish_config better handles combined term256 and classic colors like "555 yellow".
New Features
------------
* **A history builtin**, and associated interactive function that enables deleting history items. Example usage:
* Print all history items beginning with echo: `history --prefix echo`
* Print all history items containing foo: `history --contains foo`
* Interactively delete some items containing foo: `history --delete --contains foo`
Credit to @siteshwar for implementation. Thanks @siteshwar!
---
# fishfish Beta r1
## Scripting
* No changes! All existing fish scripts, config files, completions, etc. from trunk should continue to work.
## New Features
* **Autosuggestions**. Think URL fields in browsers. When you type a command, fish will suggest the rest of the command after the cursor, in a muted gray when possible. You can accept the suggestion with the right arrow key or Ctrl-F. Suggestions come from command history, completions, and some custom code for cd; there's a lot of potential for improvement here. The suggestions are computed on a background pthread, so they never slow down your typing. The autosuggestion feature is incredible. I miss it dearly every time I use anything else.
* **term256 support** where available, specifically modern xterms and OS X Lion. You can specify colors the old way ('set_color cyan') or by specifying RGB hex values ('set_color FF3333'); fish will pick the closest supported color. Some xterms do not advertise term256 support either in the $TERM or terminfo max_colors field, but nevertheless support it. For that reason, fish will default into using it on any xterm (but it can be disabled with an environment variable).
* **Web-based configuration** page. There is a new function 'fish_config'. This spins up a simple Python web server and opens a browser window to it. From this web page, you can set your shell colors and view your functions, variables, and history; all changes apply immediately to all running shells. Eventually all configuration ought to be supported via this mechanism (but in addition to, not instead of, command line mechanisms).
* **Man page completions**. There is a new function 'fish_update_completions'. This function reads all the man1 files from your manpath, removes the roff formatting, parses them to find the commands and options, and outputs fish completions into ~/.config/fish/completions. It won't overwrite existing completion files (except ones that it generated itself).
## Programmatic Changes
* fish is now entirely in C++. I have no particular love for C++, but it provides a ready memory-model to replace halloc. We've made an effort to keep it to a sane and portable subset (no C++11, no boost, no going crazy with templates or smart pointers), but we do use the STL and a little tr1.
* halloc is entirely gone, replaced by normal C++ ownership semantics. If you don't know what halloc is, well, now you have two reasons to be happy.
* All the crufty C data structures are entirely gone. array_list_t, priority_queue_t, hash_table_t, string_buffer_t have been removed and replaced by STL equivalents like std::vector, std::map, and std::wstring. A lot of the string handling now uses std::wstring instead of wchar_t *
* fish now spawns pthreads for tasks like syntax highlighting that require blocking I/O.
* History has been completely rewritten. History files now use an extensible YAML-style syntax. History "merging" (multiple shells writing to the same history file) now works better. There is now a maximum history length of about 250k items (256 * 1024).
* The parser has been "instanced," so you can now create more than one.
* Total #LoC has shrunk slightly even with the new features.
## Performance
* fish now runs syntax highlighting in a background thread, so typing commands is always responsive even on slow filesystems.
* echo, test, and pwd are now builtins, which eliminates many forks.
* The files in share/functions and share/completions now get 'internalized' into C strings that get compiled in with fish. This substantially reduces the number of files touched at startup. A consequence is that you cannot change these functions without recompiling, but often other functions depend on these "standard" functions, so changing them is perhaps not a good idea anyways.
Here are some system call counts for launching and then exiting fish with the default configuration, on OS X. The first column is fish trunk, the next column is with our changes, and the last column is bash for comparison. This data was collected via dtrace.
<table>
<tr> <th> <th> before <th> after <th> bash
<tr> <th> open <td> 9 <td> 4 <td> 5
<tr> <th> fork <td> 28 <td> 14 <td> 0
<tr> <th> stat <td> 131 <td> 85 <td> 11
<tr> <th> lstat <td> 670 <td> 0 <td> 0
<tr> <th> read <td> 332 <td> 80 <td> 4
<tr> <th> write <td> 172 <td> 149 <td> 0
</table>
The large number of forks relative to bash are due to fish's insanely expensive default prompt, which is unchanged in my version. If we switch to a prompt comparable to bash's (lame) default, the forks drop to 16 with trunk, 4 after our changes.
The large reduction in lstat() numbers is due to fish no longer needing to call ttyname() on OS X.
We've got some work to do to be as lean as bash, but we're on the right track.

View File

@@ -1,153 +0,0 @@
# Guidelines For Developers
This document provides guidelines for making changes to the fish-shell project. This includes rules for how to format the code, naming conventions, etc. It also includes recommended best practices such as creating a Travis-CI account so you can verify your changes pass all the tests before making a pull-request.
See the bottom of this document for help on installing the linting and style reformatting tools discussed in the following sections.
## Lint Free Code
Automated analysis tools like cppcheck and oclint can point out potential bugs. They also help ensure the code has a consistent style and that it avoids patterns that tend to confuse people.
Ultimately we want lint free code. However, at the moment a lot of cleanup is required to reach that goal. For now simply try to avoid introducing new lint.
To make linting the code easy there are two make targets: `lint` and `lint-all`. The latter does just what the name implies. The former will lint any modified but not committed `*.cpp` files. If there is no uncommitted work it will lint the files in the most recent commit.
### Dealing With Lint Warnings
You are strongly encouraged to address a lint warning by refactoring the code, changing variable names, or whatever action is implied by the warning.
### Suppressing Lint Warnings
Once in a while the lint tools emit a false positive warning. For example, cppcheck might suggest a memory leak is present when that is not the case. To suppress that cppcheck warning you should insert a line like the following immediately prior to the line cppcheck warned about:
```
// cppcheck-suppress memleak // addr not really leaked
```
The explanatory portion of the suppression comment is optional. For other types of warnings replace "memleak" with the value inside the parenthesis (e.g., "nullPointerRedundantCheck") from a warning like the following:
```
[src/complete.cpp:1727]: warning (nullPointerRedundantCheck): Either the condition 'cmd_node' is redundant or there is possible null pointer dereference: cmd_node.
```
Suppressing oclint warnings is more complicated to describe so I'll refer you to the [OCLint HowTo](http://docs.oclint.org/en/latest/howto/suppress.html#annotations) on the topic.
## Ensuring Your Changes Conform to the Style Guides
The following sections discuss the specific rules for the style that should be used when writing fish code. To ensure your changes conform to the style rules you simply need to run
```
make style
```
before commiting your change. If you've already committed your changes that's okay since it will then check the files in the most recent commit. This can be useful after you've merged someone elses change and want to check that it's style is acceptable.
If you want to check the style of the entire code base run
```
make style-all
```
### Suppressing Reformatting of the Code
If you have a good reason for doing so you can tell `clang-format` to not reformat a block of code by enclosing it in comments like this:
```
// clang-format off
code to ignore
// clang-format on
```
## Fish Script Style Guide
Fish scripts such as those in the *share/functions* and *tests* directories should be formatted using the `fish_indent` command.
Function names should be all lowercase with undescores separating words. Private functions should begin with an underscore. The first word should be `fish` if the function is unique to fish.
The first word of global variable names should generally be `fish` for public vars or `_fish` for private vars to minimize the possibility of name clashes with user defined vars.
## C++ Style Guide
1. The [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html) forms the basis of the fish C++ style guide. There are two major deviations for the fish project. First, a four, rather than two, space indent. Second, line lengths up to 100, rather than 80, characters.
1. The `clang-format` command is authoritative with respect to indentation, whitespace around operators, etc. **Note**: this rule should be ignored at this time. After the code is cleaned up this rule will become mandatory.
1. All names in code should be `small_snake_case`. No Hungarian notation is used. Classes and structs names should be followed by `_t`.
1. Always attach braces to the surrounding context.
1. Indent with spaces, not tabs and use four spaces per indent.
1. Comments should always use the C++ style; i.e., each line of the comment should begin with a `//` and should be limited to 100 characters. Comments that do not begin a line should be separated from the previous text by two spaces.
## Testing
The source code for fish includes a large collection of tests. If you are making any changes to fish, running these tests is highly recommended to make sure the behaviour remains consistent.
You are also strongly encouraged to add tests when changing the functionality of fish. Especially if you are fixing a bug to help ensure there are no regressions in the future (i.e., we don't reintroduce the bug).
### Local testing
The tests can be run on your local computer on all operating systems.
Running the tests is only supported from the autotools build and not xcodebuild. On OS X, you will need to install autoconf &mdash; we suggest using [Homebrew](http://brew.sh/) to install these tools.
autoconf
./configure
make test [gmake on BSD]
### Travis CI Build and Test
The Travis Continuous Integration services can be used to test your changes using multiple configurations. This is the same service that the fish shell project uses to ensure new changes haven't broken anything. Thus it is a really good idea that you leverage Travis CI before making a pull-request to avoid embarrasment at breaking the build.
You will need to [fork the fish-shell repository on GitHub](https://help.github.com/articles/fork-a-repo/). Then setup Travis to test your changes before you make a pull-request:
1. [Sign in to Travis CI](https://travis-ci.org/auth) with your GitHub account, accepting the GitHub access permissions confirmation.
1. Once you're signed in, and your repositories are synchronised, go to your [profile page](https://travis-ci.org/profile) and enable the fish-shell repository.
1. Push your changes to GitHub.
You'll receive an email when the tests are complete telling you whether or not any tests failed.
You'll find the configuration used to control Travis in the `.travis.yml` file.
## Installing the Required Tools
### Installing the Linting Tools
To install the lint checkers on Mac OS X using HomeBrew:
```
brew tap oclint/formulae
brew install oclint
brew install cppcheck
```
To install the lint checkers on Linux distros that use Apt:
```
sudo apt-get install clang
sudo apt-get install oclint
sudo apt-get install cppcheck
```
### Installing the Reformatting Tools
To install the reformatting tool on Mac OS X using HomeBrew:
```
brew install clang-format
```
To install the reformatting tool on Linux distros that use Apt:
```
apt-cache search clang-format
```
That will list the versions available. Pick the newest one available (3.6 for Ubuntu 14.04 as I write this) and install it:
```
sudo apt-get install clang-format-3.6
sudo ln -s /usr/bin/clang-format-3.6 /usr/bin/clang-format
```

19
COPYING
View File

@@ -1,19 +0,0 @@
Fish is a smart and user-friendly command line shell.
Copyright (C) 2005-2009 Axel Liljencrantz
fish is free software.
Most of fish is licensed under the GNU General Public License version 2, and
you can redistribute it and/or modify it under the terms of the GNU GPL as
published by the Free Software Foundation.
fish also includes software licensed under the GNU Lesser General Public
License version 2, the OpenBSD license and the ISC license.
Full licensing information is contained in doc_src/license.hdr.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.

View File

@@ -1,19 +0,0 @@
FROM centos:latest
# Build dependency
RUN yum update -y &&\
yum install -y autoconf automake bc clang gcc-c++ make ncurses-devel &&\
yum clean all
# Test dependency
RUN yum install -y expect vim-common
ADD . /src
WORKDIR /src
# Build fish
RUN autoreconf &&\
./configure &&\
make &&\
make install

2408
Doxyfile

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,33 +1,25 @@
[fish](http://fishshell.com/) - the friendly interactive shell [![Build Status](https://travis-ci.org/fish-shell/fish-shell.svg?branch=master)](https://travis-ci.org/fish-shell/fish-shell) [fish](http://ridiculousfish.com/shell/) - the friendly interactive shell
================================================ ================================================
fish is a smart and user-friendly command line shell for OS X, Linux, and the rest of the family. fish includes features like syntax highlighting, autosuggest-as-you-type, and fancy tab completions that just work, with no configuration required. fish is a smart and user-friendly command line shell for OS X, Linux, and the rest of the family. fish includes features like syntax highlighting, autosuggest-as-you-type, and fancy tab completions that just work, with no configuration required.
For more on fish's design philosophy, see the [design document](http://fishshell.com/docs/current/design.html). For more on fish's design philosophy, see the [design document](http://ridiculousfish.com/shell/user_doc/html/design.html).
## Quick Start ## Quick Start
fish generally works like other shells, like bash or zsh. A few important differences can be found at <http://fishshell.com/docs/current/tutorial.html> by searching for the magic phrase "unlike other shells". fish generally works like other shells, like bash or zsh. A few important differences are documented at <http://ridiculousfish.com/shell/faq.html>
Detailed user documentation is available by running `help` within fish, and also at <http://fishshell.com/docs/current/index.html> Detailed user documentation is available by running `help` within fish, and also at <http://ridiculousfish.com/shell/user_doc/html/>
## Building ## Building
fish is written in a sane subset of C++98, with a few components from C++TR1. It builds successfully with g++ 4.2 or later, and with clang. It also will build as C++11. fish is written in a sane subset of C++98, with a few components from C++TR1. It builds successfully with g++ 4.2 or later, and with clang. It also will build as C++11.
fish can be built using autotools or Xcode. autoconf 2.60 or later is required to build from git versions, but is not required for releases. fish can be built using autotools or Xcode.
fish depends on a curses implementation, such as ncurses. The headers and libraries are required for building.
fish requires PCRE2 due to the regular expression support contained in the `string` builtin. A copy is included with the source code, and will be used automatically if it does not already exist on your system.
fish requires gettext for translation support.
Building the documentation requires Doxygen 1.8.7 or newer.
### Autotools Build ### Autotools Build
autoconf [if building from Git] autoconf
./configure ./configure
make [gmake on BSD] make [gmake on BSD]
sudo make install sudo make install
@@ -48,29 +40,15 @@ If fish reports that it could not find curses, try installing a curses developme
On Debian or Ubuntu you want: On Debian or Ubuntu you want:
sudo apt-get install build-essential ncurses-dev libncurses5-dev gettext autoconf sudo apt-get install libncurses5-dev libncursesw5-dev
On RedHat, CentOS, or Amazon EC2: on RedHat, CentOS, or Amazon EC2:
sudo yum install ncurses-devel sudo yum install ncurses-devel
## Runtime Dependencies
fish requires a curses implementation, such as ncurses, to run.
fish requires PCRE2 due to the regular expression support contained in the `string` builtin. A bundled version will be compiled in automatically at build time if required.
fish requires a number of utilities to operate, which should be present on any Unix, GNU/Linux or OS X system. These include (but are not limited to) hostname, grep, awk, sed, which, and getopt. fish also requires the bc program.
Translation support requires the gettext program.
Some optional features of fish, such as the manual page completion parser and the web configuration tool, require Python.
In order to generate completions from man pages compressed with either lzma or xz, you may need to install an extra Python package. Python versions prior to 2.6 are not supported. For Python versions 2.6 to 3.2 you need to install the module `backports.lzma`. How to install it depends on your system and how you installed Python. Most Linux distributions should include it as a package named `backports-lzma` (or similar). From version 3.3 onwards, Python already includes the required module.
## Packages for Linux ## Packages for Linux
Instructions on how to find builds for several Linux distros are at <https://github.com/fish-shell/fish-shell/wiki/Nightly-builds> Nightly builds for several Linux distros can be downloaded from <http://download.opensuse.org/repositories/home:/siteshwar/>
## Switching to fish ## Switching to fish
@@ -78,11 +56,7 @@ If you wish to use fish as your default shell, use the following command:
chsh -s /usr/local/bin/fish chsh -s /usr/local/bin/fish
chsh will prompt you for your password, and change your default shell. Substitute "/usr/local/bin/fish" with whatever path to fish is in your /etc/shells file. chsh will prompt you for your password, and change your default shell.
Use the following command if you didn't already add your fish path to /etc/shells.
echo /usr/local/bin/fish | sudo tee -a /etc/shells
To switch your default shell back, you can run: To switch your default shell back, you can run:
@@ -90,12 +64,8 @@ To switch your default shell back, you can run:
Substitute /bin/bash with /bin/tcsh or /bin/zsh as appropriate. Substitute /bin/bash with /bin/tcsh or /bin/zsh as appropriate.
## Contributing Changes to the Code
See the [Guide for Developers](CONTRIBUTING.md).
## Contact Us ## Contact Us
Questions, comments, rants and raves can be posted to the official fish mailing list at <https://lists.sourceforge.net/lists/listinfo/fish-users> or join us on our [gitter.im channel](https://gitter.im/fish-shell/fish-shell) or IRC channel [#fish at irc.oftc.net](https://webchat.oftc.net/?channels=fish). Or use the [fish tag on Stackoverflow](https://stackoverflow.com/questions/tagged/fish). Questions, comments, rants and raves can be posted to the official fish mailing list at <https://lists.sourceforge.net/lists/listinfo/fish-users> or join us on our IRC channel #fish at irc.oftc.net
Found a bug? Have an awesome idea? Please open an issue on this github page. Found a bug? Have an awesome idea? Please open an issue on this github page.

105
STYLEGUIDE.md Normal file
View File

@@ -0,0 +1,105 @@
# Style guide
This is style guide for fish contributors. You should use it for any new code
that you would add to this project and try to format existing code to use this
style.
## Formatting
1. fish uses the Allman/BSD style of indentation.
2. Indent with spaces, not tabs.
3. Use 4 spaces per indent (unless needed like `Makefile`).
4. Opening curly bracket is on the following line:
// ✔:
struct name
{
// code
};
void func()
{
// code
}
if (...)
{
// code
}
// ✗:
void func() {
// code
}
5. Put space after `if`, `while` and `for` before conditions.
// ✔:
if () {}
// ✗:
if() {}
6. Put spaces before and after operators excluding increment and decrement;
// ✔:
int a = 1 + 2 * 3;
a++;
// ✗:
int a=1+2*3;
a ++;
7. Never put spaces between function name and parameters list.
// ✔:
func(args);
// ✗:
func (args);
8. Never put spaces after `(` and before `)`.
9. Always put space after comma and semicolon.
// ✔:
func(arg1, arg2);
for (int i = 0; i < LENGTH; i++) {}
// ✗:
func(arg1,arg2);
for (int i = 0;i<LENGTH;i++) {}
## Documentation
Document your code using [Doxygen][dox].
1. Documentation comment should use double star notation or tripple slash:
// ✔:
/// Some var
int var;
/**
* Some func
*/
void func();
2. Use slash as tag mark:
// ✔:
/**
* \param a an integer argument.
* \param s a constant character pointer.
* \return The results
*/
int foo(int a, const char *s);
## Naming
All names in code should be `small_snake_case`. No Hungarian notation is used.
Classes and structs names should be followed by `_t`.
[dox]: http://www.stack.nl/~dimitri/doxygen/ "Doxygen homepage"

View File

@@ -3,21 +3,14 @@
The classes responsible for autoloading functions and completions. The classes responsible for autoloading functions and completions.
*/ */
#include "config.h" // IWYU pragma: keep #include "config.h"
#include "autoload.h" #include "autoload.h"
#include "wutil.h" #include "wutil.h"
#include "common.h" #include "common.h"
#include "signal.h" // IWYU pragma: keep - needed for CHECK_BLOCK #include "signal.h"
#include "env.h" #include "env.h"
#include "exec.h" #include "exec.h"
#include <assert.h> #include <assert.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <wchar.h>
#include <string>
#include <utility>
#include <vector>
#include <algorithm> #include <algorithm>
/* The time before we'll recheck an autoloaded file */ /* The time before we'll recheck an autoloaded file */
@@ -26,7 +19,7 @@ static const int kAutoloadStalenessInterval = 15;
file_access_attempt_t access_file(const wcstring &path, int mode) file_access_attempt_t access_file(const wcstring &path, int mode)
{ {
//printf("Touch %ls\n", path.c_str()); //printf("Touch %ls\n", path.c_str());
file_access_attempt_t result = {}; file_access_attempt_t result = {0};
struct stat statbuf; struct stat statbuf;
if (wstat(path, &statbuf)) if (wstat(path, &statbuf))
{ {
@@ -55,7 +48,9 @@ autoload_t::autoload_t(const wcstring &env_var_name_var, const builtin_script_t
lock(), lock(),
env_var_name(env_var_name_var), env_var_name(env_var_name_var),
builtin_scripts(scripts), builtin_scripts(scripts),
builtin_script_count(script_count) builtin_script_count(script_count),
last_path(),
is_loading_set()
{ {
pthread_mutex_init(&lock, NULL); pthread_mutex_init(&lock, NULL);
} }
@@ -71,7 +66,7 @@ void autoload_t::node_was_evicted(autoload_function_t *node)
ASSERT_IS_MAIN_THREAD(); ASSERT_IS_MAIN_THREAD();
// Tell ourselves that the command was removed if it was loaded // Tell ourselves that the command was removed if it was loaded
if (node->is_loaded) if (! node->is_loaded)
this->command_removed(node->key); this->command_removed(node->key);
delete node; delete node;
} }
@@ -99,34 +94,33 @@ int autoload_t::load(const wcstring &cmd, bool reload)
if (path_var != this->last_path) if (path_var != this->last_path)
{ {
this->last_path = path_var; this->last_path = path_var;
this->last_path_tokenized.clear();
tokenize_variable_array(this->last_path, this->last_path_tokenized);
scoped_lock locker(lock); scoped_lock locker(lock);
this->evict_all_nodes(); this->evict_all_nodes();
} }
/* Mark that we're loading this. Hang onto the iterator for fast erasing later. Note that std::set has guarantees about not invalidating iterators, so this is safe to do across the callouts below. */
typedef std::set<wcstring>::iterator set_iterator_t;
std::pair<set_iterator_t, bool> insert_result = is_loading_set.insert(cmd);
set_iterator_t where = insert_result.first;
bool inserted = insert_result.second;
/** Warn and fail on infinite recursion. It's OK to do this because this function is only called on the main thread. */ /** Warn and fail on infinite recursion. It's OK to do this because this function is only called on the main thread. */
if (! inserted) if (this->is_loading(cmd))
{ {
/* We failed to insert */
debug(0, debug(0,
_(L"Could not autoload item '%ls', it is already being autoloaded. " _(L"Could not autoload item '%ls', it is already being autoloaded. "
L"This is a circular dependency in the autoloading scripts, please remove it."), L"This is a circular dependency in the autoloading scripts, please remove it."),
cmd.c_str()); cmd.c_str());
return 1; return 1;
} }
/* Mark that we're loading this */
is_loading_set.insert(cmd);
/* Get the list of paths from which we will try to load */
std::vector<wcstring> path_list;
tokenize_variable_array(path_var, path_list);
/* Try loading it */ /* Try loading it */
res = this->locate_file_and_maybe_load_it(cmd, true, reload, this->last_path_tokenized); res = this->locate_file_and_maybe_load_it(cmd, true, reload, path_list);
/* Clean up */ /* Clean up */
is_loading_set.erase(where); bool erased = !! is_loading_set.erase(cmd);
assert(erased);
return res; return res;
} }
@@ -147,6 +141,12 @@ static bool script_name_precedes_script_name(const builtin_script_t &script1, co
return wcscmp(script1.name, script2.name) < 0; return wcscmp(script1.name, script2.name) < 0;
} }
void autoload_t::unload_all(void)
{
scoped_lock locker(lock);
this->evict_all_nodes();
}
/** Check whether the given command is loaded. */ /** Check whether the given command is loaded. */
bool autoload_t::has_tried_loading(const wcstring &cmd) bool autoload_t::has_tried_loading(const wcstring &cmd)
{ {
@@ -195,6 +195,7 @@ autoload_function_t *autoload_t::get_autoloaded_function_with_creation(const wcs
bool autoload_t::locate_file_and_maybe_load_it(const wcstring &cmd, bool really_load, bool reload, const wcstring_list_t &path_list) bool autoload_t::locate_file_and_maybe_load_it(const wcstring &cmd, bool really_load, bool reload, const wcstring_list_t &path_list)
{ {
/* Note that we are NOT locked in this function! */ /* Note that we are NOT locked in this function! */
size_t i;
bool reloaded = 0; bool reloaded = 0;
/* Try using a cached function. If we really want the function to be loaded, require that it be really loaded. If we're not reloading, allow stale functions. */ /* Try using a cached function. If we really want the function to be loaded, require that it be really loaded. If we're not reloading, allow stale functions. */
@@ -233,7 +234,6 @@ bool autoload_t::locate_file_and_maybe_load_it(const wcstring &cmd, bool really_
/* If we can use this function, return whether we were able to access it */ /* If we can use this function, return whether we were able to access it */
if (use_cached) if (use_cached)
{ {
assert(func != NULL);
return func->is_internalized || func->access.accessible; return func->is_internalized || func->access.accessible;
} }
} }
@@ -276,7 +276,7 @@ bool autoload_t::locate_file_and_maybe_load_it(const wcstring &cmd, bool really_
if (! has_script_source) if (! has_script_source)
{ {
/* Iterate over path searching for suitable completion files */ /* Iterate over path searching for suitable completion files */
for (size_t i=0; i<path_list.size(); i++) for (i=0; i<path_list.size(); i++)
{ {
wcstring next = path_list.at(i); wcstring next = path_list.at(i);
wcstring path = next + L"/" + cmd + L".fish"; wcstring path = next + L"/" + cmd + L".fish";
@@ -298,7 +298,7 @@ bool autoload_t::locate_file_and_maybe_load_it(const wcstring &cmd, bool really_
/* Generate the script source */ /* Generate the script source */
wcstring esc = escape_string(path, 1); wcstring esc = escape_string(path, 1);
script_source = L"source " + esc; script_source = L". " + esc;
has_script_source = true; has_script_source = true;
/* Remove any loaded command because we are going to reload it. Note that this will deadlock if command_removed calls back into us. */ /* Remove any loaded command because we are going to reload it. Note that this will deadlock if command_removed calls back into us. */

View File

@@ -6,10 +6,10 @@
#ifndef FISH_AUTOLOAD_H #ifndef FISH_AUTOLOAD_H
#define FISH_AUTOLOAD_H #define FISH_AUTOLOAD_H
#include <pthread.h> #include <wchar.h>
#include <stddef.h> #include <map>
#include <time.h>
#include <set> #include <set>
#include <list>
#include "common.h" #include "common.h"
#include "lru.h" #include "lru.h"
@@ -27,7 +27,7 @@ file_access_attempt_t access_file(const wcstring &path, int mode);
struct autoload_function_t : public lru_node_t struct autoload_function_t : public lru_node_t
{ {
explicit autoload_function_t(const wcstring &key) : lru_node_t(key), access(), is_loaded(false), is_placeholder(false), is_internalized(false) { } autoload_function_t(const wcstring &key) : lru_node_t(key), access(), is_loaded(false), is_placeholder(false), is_internalized(false) { }
file_access_attempt_t access; /** The last access attempt */ file_access_attempt_t access; /** The last access attempt */
bool is_loaded; /** Whether we have actually loaded this function */ bool is_loaded; /** Whether we have actually loaded this function */
bool is_placeholder; /** Whether we are a placeholder that stands in for "no such function". If this is true, then is_loaded must be false. */ bool is_placeholder; /** Whether we are a placeholder that stands in for "no such function". If this is true, then is_loaded must be false. */
@@ -40,6 +40,7 @@ struct builtin_script_t
const char *def; const char *def;
}; };
struct builtin_script_t;
class env_vars_snapshot_t; class env_vars_snapshot_t;
/** /**
@@ -64,15 +65,17 @@ class autoload_t : private lru_cache_t<autoload_function_t>
/** The path from which we most recently autoloaded */ /** The path from which we most recently autoloaded */
wcstring last_path; wcstring last_path;
/** That path, tokenized (split on separators) */
wcstring_list_t last_path_tokenized;
/** /**
A table containing all the files that are currently being A table containing all the files that are currently being
loaded. This is here to help prevent recursion. loaded. This is here to help prevent recursion.
*/ */
std::set<wcstring> is_loading_set; std::set<wcstring> is_loading_set;
bool is_loading(const wcstring &name) const
{
return is_loading_set.find(name) != is_loading_set.end();
}
void remove_all_functions(void) void remove_all_functions(void)
{ {
this->evict_all_nodes(); this->evict_all_nodes();
@@ -122,6 +125,11 @@ class autoload_t : private lru_cache_t<autoload_function_t>
*/ */
int unload(const wcstring &cmd); int unload(const wcstring &cmd);
/**
Unloads all files.
*/
void unload_all();
/** Check whether the given command could be loaded, but do not load it. */ /** Check whether the given command could be loaded, but do not load it. */
bool can_load(const wcstring &cmd, const env_vars_snapshot_t &vars); bool can_load(const wcstring &cmd, const env_vars_snapshot_t &vars);

View File

@@ -20,8 +20,10 @@ else
fi fi
# Determine which man pages we don't want to generate. # Determine which man pages we don't want to generate.
# Don't make a test man page. fish's test is conforming, so the system man pages
# are applicable and generally better.
# on OS X, don't make a man page for open, since we defeat fish's open function on OS X. # on OS X, don't make a man page for open, since we defeat fish's open function on OS X.
CONDEMNED_PAGES= CONDEMNED_PAGES=test.1
if test `uname` = 'Darwin'; then if test `uname` = 'Darwin'; then
CONDEMNED_PAGES="$CONDEMNED_PAGES open.1" CONDEMNED_PAGES="$CONDEMNED_PAGES open.1"
fi fi
@@ -37,12 +39,10 @@ resolve_path()
# Expand relative paths # Expand relative paths
DOXYFILE=`resolve_path "$DOXYFILE"` DOXYFILE=`resolve_path "$DOXYFILE"`
INPUTDIR=`resolve_path "$INPUTDIR"` INPUTDIR=`resolve_path "$INPUTDIR"`
INPUTFILTER=`resolve_path "$INPUT_FILTER"`
OUTPUTDIR=`resolve_path "$OUTPUTDIR"` OUTPUTDIR=`resolve_path "$OUTPUTDIR"`
echo " doxygen file: $DOXYFILE" echo " doxygen file: $DOXYFILE"
echo " input directory: $INPUTDIR" echo " input directory: $INPUTDIR"
echo " input filter: $INPUTFILTER"
echo " output directory: $OUTPUTDIR" echo " output directory: $OUTPUTDIR"
echo " skipping: $CONDEMNED_PAGES" echo " skipping: $CONDEMNED_PAGES"
@@ -68,12 +68,6 @@ if test -z "$DOXYGENPATH"; then
exit 0 exit 0
fi fi
# Check we have the lexicon filter
if test -z "$INPUT_FILTER"; then
echo >&2 "Lexicon filter is not available. Continuing without."
INPUTFILTER=''
fi
# Determine where our output should go # Determine where our output should go
if ! mkdir -p "${OUTPUTDIR}" ; then if ! mkdir -p "${OUTPUTDIR}" ; then
echo "Could not create output directory '${OUTPUTDIR}'" echo "Could not create output directory '${OUTPUTDIR}'"
@@ -94,8 +88,7 @@ done
# Input is kept as . because we cd to the input directory beforehand # Input is kept as . because we cd to the input directory beforehand
# This prevents doxygen from generating "documentation" for intermediate directories # This prevents doxygen from generating "documentation" for intermediate directories
DOXYPARAMS=$(cat <<EOF DOXYPARAMS=$(cat <<EOF
PROJECT_NUMBER=$PROJECT_NUMBER PROJECT_NUMBER=2.0.0
INPUT_FILTER=$INPUTFILTER
INPUT=. INPUT=.
OUTPUT_DIRECTORY=$OUTPUTDIR OUTPUT_DIRECTORY=$OUTPUTDIR
QUIET=YES QUIET=YES
@@ -109,7 +102,7 @@ find "${OUTPUTDIR}" -name "*.1" -delete
# Run doxygen # Run doxygen
cd "$TMPLOC" cd "$TMPLOC"
(cat "${DOXYFILE}" ; echo "$DOXYPARAMS";) | "$DOXYGENPATH" - (cat "${DOXYFILE}" ; echo "$DOXYPARAMS";) | "$DOXYGENPATH" -
# Remember errors # Remember errors
RESULT=$? RESULT=$?
@@ -119,16 +112,15 @@ if test "$RESULT" = 0 ; then
# Postprocess the files # Postprocess the files
for i in "$INPUTDIR"/*.txt; do for i in "$INPUTDIR"/*.txt; do
# It would be nice to use -i here for edit in place, but that is not portable # It would be nice to use -i here for edit in place, but that is not portable
CMD_NAME=`basename "$i" .txt`; CMD_NAME=`basename "$i" .txt`;
sed < ${CMD_NAME}.1 > ${CMD_NAME}.1.tmp \ sed -e "s/\(.\)\\.SH/\1/" -e "s/$CMD_NAME *\\\\- *\"\(.*\)\"/\1/" "${CMD_NAME}.1" > "${CMD_NAME}.1.tmp"
-e "/.SH \"$CMD_NAME/d" \
-e "s/^$CMD_NAME * \\\- \([^ ]*\) /\\\fB\1\\\fP -/"
mv "${CMD_NAME}.1.tmp" "${CMD_NAME}.1" mv "${CMD_NAME}.1.tmp" "${CMD_NAME}.1"
done done
# Erase condemned pages # Erase condemned pages
rm -f $CONDEMNED_PAGES rm -f $CONDEMNED_PAGES
fi fi
# Destroy TMPLOC # Destroy TMPLOC

View File

@@ -1,3 +0,0 @@
#!/usr/local/bin/fish
cppcheck --enable=all --std=posix --quiet .

View File

@@ -1,28 +0,0 @@
#!/bin/sh
# Originally from the git sources (GIT-VERSION-GEN)
# Presumably (C) Junio C Hamano <junkio@cox.net>
# Reused under GPL v2.0
# Modified for fish by David Adam <zanchey@ucc.gu.uwa.edu.au>
FBVF=FISH-BUILD-VERSION-FILE
DEF_VER=unknown
# First see if there is a version file (included in release tarballs),
# then try git-describe, then default.
if test -f version
then
VN=$(cat version) || VN="$DEF_VER"
elif ! VN=$(git describe --always --dirty 2>/dev/null); then
VN="$DEF_VER"
fi
if test -r $FBVF
then
VC=$(sed -e 's/^FISH_BUILD_VERSION = //' <$FBVF)
else
VC=unset
fi
test "$VN" = "$VC" || {
echo >&2 "FISH_BUILD_VERSION = $VN"
echo "FISH_BUILD_VERSION = $VN" >$FBVF
}

View File

@@ -1,4 +0,0 @@
#!/bin/sh
# Reminder of how to run Include What You Use
make iwyu

View File

@@ -1,100 +0,0 @@
#!/usr/bin/env fish
#
# This is meant to be run by "make lint" or "make lint-all". It is not meant to
# be run directly from a shell prompt.
#
set cppchecks warning,performance,portability,information,missingInclude
set cppcheck_args
set c_files
set all no
set -gx CXX $argv[1]
set -e argv[1]
if test "$argv[1]" = "--all"
set all yes
set cppchecks "$cppchecks,unusedFunction"
set -e argv[1]
end
# We only want -D and -I options to be passed thru to cppcheck.
for arg in $argv
if string match -q -- '-D*' $arg
set cppcheck_args $cppcheck_args $arg
else if string match -q -- '-I*' $arg
set cppcheck_args $cppcheck_args $arg
end
end
if test (uname -m) = "x86_64"
set cppcheck_args -D__x86_64__ -D__LP64__ $cppcheck_args
end
if test $all = yes
set c_files src/*.cpp
else
# We haven't been asked to lint all the source. If there are uncommitted
# changes lint those, else lint the files in the most recent commit.
set pending (git status --porcelain --short --untracked-files=all | sed -e 's/^ *//')
if set -q pending[1]
# There are pending changes so lint those files.
for arg in $pending
set files $files (string split -m 1 ' ' $arg)[2]
end
else
# No pending changes so lint the files in the most recent commit.
set files (git show --word-diff=porcelain --name-only --pretty=oneline head)[2..-1]
end
# Extract just the C/C++ files.
set c_files (string match -r '.*\.c(?:pp)?$' -- $files)
end
# We now have a list of files to check so run the linters.
if set -q c_files[1]
if type -q cppcheck
echo
echo ========================================
echo Running cppcheck
echo ========================================
# The stderr to stdout redirection is because cppcheck, incorrectly
# IMHO, writes its diagnostic messages to stderr. Anyone running
# this who wants to capture its output will expect those messages to be
# written to stdout.
cppcheck -q --verbose --std=posix --std=c11 --language=c++ --template "[{file}:{line}]: {severity} ({id}): {message}" --suppress=missingIncludeSystem --inline-suppr --enable=$cppchecks $cppcheck_args $c_files 2>& 1
end
if type -q oclint
echo
echo ========================================
echo Running oclint
echo ========================================
# The stderr to stdout redirection is because oclint, incorrectly
# writes its final summary counts of the errors detected to stderr.
# Anyone running this who wants to capture its output will expect those
# messages to be written to stdout.
if test (uname -s) = "Darwin"
if not test -f compile_commands.json
xcodebuild > xcodebuild.log
oclint-xcodebuild xcodebuild.log > /dev/null
end
if test $all = yes
oclint-json-compilation-database -e '/pcre2-10.21/' -- -enable-global-analysis 2>& 1
else
set i_files
for f in $c_files
set i_files $i_files -i $f
end
echo oclint-json-compilation-database -e '/pcre2-10.21/' $i_files
oclint-json-compilation-database -e '/pcre2-10.21/' $i_files 2>& 1
end
else
# Presumably we're on Linux or other platform not requiring special
# handling for oclint to work.
oclint $c_files -- $argv 2>& 1
end
end
else
echo
echo 'WARNING: No C/C++ files to check'
echo
end

View File

@@ -21,10 +21,3 @@ xcodebuild install -scheme install_tree -configuration Release DSTROOT=/tmp/fish
pkgbuild --scripts build_tools/osx_package_scripts --root /tmp/fish_pkg/root/ --identifier 'com.ridiculousfish.fish-shell-pkg' --version "$VERSION" /tmp/fish_pkg/intermediates/fish.pkg pkgbuild --scripts build_tools/osx_package_scripts --root /tmp/fish_pkg/root/ --identifier 'com.ridiculousfish.fish-shell-pkg' --version "$VERSION" /tmp/fish_pkg/intermediates/fish.pkg
productbuild --package-path /tmp/fish_pkg/intermediates --distribution build_tools/osx_distribution.xml --resources build_tools/osx_package_resources/ ~/fish_built/fish.pkg productbuild --package-path /tmp/fish_pkg/intermediates --distribution build_tools/osx_distribution.xml --resources build_tools/osx_package_resources/ ~/fish_built/fish.pkg
# Make the app
xcodebuild -scheme fish.app -configuration Release DSTROOT=/tmp/fish_app/
rm -f ~/fish_built/fish.app.zip
cd DerivedData/fish/Build/Products/Release/
zip -r ~/fish_built/fish.app.zip fish.app

View File

@@ -19,35 +19,23 @@ wd="$PWD"
# The name of the prefix, which is the directory that you get when you untar # The name of the prefix, which is the directory that you get when you untar
prefix="fish" prefix="fish"
# Get the version from git-describe
VERSION=`git describe --dirty 2>/dev/null`
prefix="$prefix-$VERSION"
# The path where we will output the tar file # The path where we will output the tar file
path=~/fish_built/$prefix.tar path=~/fish_built/fish-2.0.tar
# Clean up stuff we've written before # Clean up stuff we've written before
rm -f "$path" "$path".gz rm -f "$path" "$path".gz
# git starts the archive # git starts the archive
git archive --format=tar --prefix="$prefix"/ HEAD > "$path" git archive --format=tar --prefix="$prefix"/ master > "$path"
# tarball out the documentation, generate a configure script and version file # tarball out the documentation
# Don't use autoreconf since it invokes commands that may not be installed, like aclocal make user_doc
# Don't run autoheader since configure.ac runs it. autoconf is enough. make share/man
autoconf
./configure --with-doxygen
make doc share/man
echo $VERSION > version
cd /tmp cd /tmp
rm -f "$prefix" rm -f "$prefix"
ln -s "$wd" "$prefix" ln -s "$wd" "$prefix"
TAR_APPEND="gnutar --append --file=$path --mtime=now --owner=0 --group=0 --mode=g+w,a+rX" tar --append --file="$path" "$prefix"/user_doc/html
$TAR_APPEND --no-recursion "$prefix"/user_doc tar --append --file="$path" "$prefix"/share/man
$TAR_APPEND "$prefix"/user_doc/html "$prefix"/share/man
$TAR_APPEND "$prefix"/version
$TAR_APPEND "$prefix"/configure "$prefix"/config.h.in
rm -f "$prefix"/version
rm -f "$prefix" rm -f "$prefix"
# gzip it # gzip it

View File

@@ -1,90 +0,0 @@
#!/usr/bin/env fish
#
# This is meant to be run by "make style" or "make style-all". It is not meant to
# be run directly from a shell prompt although it can be.
#
# This runs C++ files and fish scripts (*.fish) through their respective code
# formatting programs.
#
set c_files
set f_files
set all no
if test "$argv[1]" = "--all"
set all yes
set -e argv[1]
end
if set -q argv[1]
echo "Unexpected arguments: '$argv'"
exit 1
end
if test $all = yes
set c_files src/*.h src/*.cpp
set f_files ***.fish
else
# We haven't been asked to reformat all the source. If there are uncommitted
# changes reformat those, else reformat the files in the most recent commit.
set pending (git status --porcelain --short --untracked-files=all | sed -e 's/^ *//')
if count $pending > /dev/null
# There are pending changes so lint those files.
for arg in $pending
set files $files (string split -m 1 ' ' $arg)[2]
end
else
# No pending changes so lint the files in the most recent commit.
set files (git show --name-only --pretty=oneline head | tail --lines=+2)
end
# Extract just the C/C++ files.
set c_files (string match -r '^.*\.(?:c|cpp|h)$' -- $files)
# Extract just the fish files.
set f_files (string match -r '^.*\.fish$' -- $files)
end
# Run the C++ reformatter if we have any C++ files.
if set -q c_files[1]
if type -q clang-format
echo
echo ========================================
echo Running clang-format
echo ========================================
for file in $c_files
clang-format $file > $file.new
if cmp --quiet $file $file.new
echo $file was correctly formatted
rm $file.new
else
echo $file was NOT correctly formatted
mv $file.new $file
end
end
else
echo
echo 'WARNING: Cannot find clang-format command'
echo
end
end
# Run the fish reformatter if we have any fish files.
if set -q f_files[1]
if not type -q fish_indent
make fish_indent
set PATH . $PATH
end
echo
echo ========================================
echo Running fish_indent
echo ========================================
for file in $f_files
fish_indent < $file > $file.new
if cmp --quiet $file $file.new
echo $file was correctly formatted
rm $file.new
else
echo $file was NOT correctly formatted
mv $file.new $file
end
end
end

View File

@@ -1,17 +0,0 @@
#!/bin/bash
# Expects to be called from Xcode (Run Script build phase),
# write version number C preprocessor macro to header file.
tmp="$SCRIPT_OUTPUT_FILE_1"
ver="$SCRIPT_OUTPUT_FILE_0"
./build_tools/git_version_gen.sh
cat FISH-BUILD-VERSION-FILE | awk '{printf("#define %s \"%s\"\n",$1,$3)}' > "$tmp"
cmp --quiet "$tmp" "$ver"
if [ $? -ne 0 ]; then
/bin/mv "$tmp" "$ver"
else
/bin/rm "$tmp"
fi

File diff suppressed because it is too large Load Diff

View File

@@ -5,13 +5,12 @@
#ifndef FISH_BUILTIN_H #ifndef FISH_BUILTIN_H
#define FISH_BUILTIN_H #define FISH_BUILTIN_H
#include <stddef.h> // for size_t #include <wchar.h>
#include <vector> // for vector
#include "util.h"
#include "io.h" #include "io.h"
#include "common.h" #include "common.h"
class completion_t;
class parser_t; class parser_t;
enum enum
@@ -25,7 +24,7 @@ enum
/** /**
Error message on missing argument Error message on missing argument
*/ */
#define BUILTIN_ERR_MISSING _( L"%ls: Expected argument for option %ls\n" ) #define BUILTIN_ERR_MISSING _( L"%ls: Expected argument\n" )
/** /**
Error message on invalid combination of options Error message on invalid combination of options
@@ -62,13 +61,57 @@ enum
*/ */
#define BUILTIN_ERR_VARNAME_ZERO _( L"%ls: Variable name can not be the empty string\n" ) #define BUILTIN_ERR_VARNAME_ZERO _( L"%ls: Variable name can not be the empty string\n" )
/**
Error message when second argument to for isn't 'in'
*/
#define BUILTIN_FOR_ERR_IN _( L"%ls: Second argument must be 'in'\n" )
/**
Error message for insufficient number of arguments
*/
#define BUILTIN_FOR_ERR_COUNT _( L"%ls: Expected at least two arguments, got %d\n")
#define BUILTIN_FOR_ERR_NAME _( L"%ls: '%ls' is not a valid variable name\n" )
/** Error messages for 'else if' */
#define BUILTIN_ELSEIF_ERR_COUNT _( L"%ls: can only take 'if' and then another command as an argument\n")
#define BUILTIN_ELSEIF_ERR_ARGUMENT _( L"%ls: any second argument must be 'if'\n")
/** /**
Error message when too many arguments are supplied to a builtin Error message when too many arguments are supplied to a builtin
*/ */
#define BUILTIN_ERR_TOO_MANY_ARGUMENTS _( L"%ls: Too many arguments\n" ) #define BUILTIN_ERR_TOO_MANY_ARGUMENTS _( L"%ls: Too many arguments\n" )
/**
Error message when block types mismatch in the end builtin, e.g. 'begin; end for'
*/
#define BUILTIN_END_BLOCK_MISMATCH _( L"%ls: Block mismatch: '%ls' vs. '%ls'\n" )
/**
Error message for unknown block type in the end builtin, e.g. 'begin; end beggin'
*/
#define BUILTIN_END_BLOCK_UNKNOWN _( L"%ls: Unknown block type '%ls'\n" )
#define BUILTIN_ERR_NOT_NUMBER _( L"%ls: Argument '%ls' is not a number\n" ) #define BUILTIN_ERR_NOT_NUMBER _( L"%ls: Argument '%ls' is not a number\n" )
/** Get the string used to represent stdout and stderr */
const wcstring &get_stdout_buffer();
const wcstring &get_stderr_buffer();
/** Output an error */
void builtin_show_error(const wcstring &err);
/**
Kludge. Tells builtins if output is to screen
*/
extern int builtin_out_redirect;
/**
Kludge. Tells builtins if error is to screen
*/
extern int builtin_err_redirect;
/** /**
Initialize builtin data. Initialize builtin data.
*/ */
@@ -96,13 +139,24 @@ int builtin_exists(const wcstring &cmd);
\return the exit status of the builtin command \return the exit status of the builtin command
*/ */
int builtin_run(parser_t &parser, const wchar_t * const *argv, io_streams_t &streams); int builtin_run(parser_t &parser, const wchar_t * const *argv, const io_chain_t &io);
/** Returns a list of all builtin names */ /** Returns a list of all builtin names */
wcstring_list_t builtin_get_names(); wcstring_list_t builtin_get_names(void);
/** Insert all builtin names into list. */ /** Insert all builtin names into list. */
void builtin_get_names(std::vector<completion_t> *list); void builtin_get_names(std::vector<completion_t> &list);
/**
Pushes a new set of input/output to the stack. The new stdin is supplied, a new set of output strings is created.
*/
void builtin_push_io(parser_t &parser, int stdin_fd);
/**
Pops a set of input/output from the stack. The output strings are destroued, but the input file is not closed.
*/
void builtin_pop_io(parser_t &parser);
/** /**
Return a one-line description of the specified builtin. Return a one-line description of the specified builtin.
@@ -110,35 +164,19 @@ void builtin_get_names(std::vector<completion_t> *list);
wcstring builtin_get_desc(const wcstring &b); wcstring builtin_get_desc(const wcstring &b);
/**
/** Support for setting and removing transient command lines. Slightly kludgy function used with 'complete -C' in order to make
This is used by 'complete -C' in order to make the commandline builtin operate on the string to complete instead
the commandline builtin operate on the string to complete instead of operating on whatever is to be completed.
of operating on whatever is to be completed. It's also used by
completion wrappers, to allow a command to appear as the command
being wrapped for the purposes of completion.
Instantiating an instance of builtin_commandline_scoped_transient_t
pushes the command as the new transient commandline. The destructor removes it.
It will assert if construction/destruction does not happen in a stack-like (LIFO) order.
*/ */
class builtin_commandline_scoped_transient_t const wchar_t *builtin_complete_get_temporary_buffer();
{
size_t token;
public:
explicit builtin_commandline_scoped_transient_t(const wcstring &cmd);
~builtin_commandline_scoped_transient_t();
};
/** /**
Run the __fish_print_help function to obtain the help information Run the __fish_print_help function to obtain the help information
for the specified command. for the specified command.
*/ */
wcstring builtin_help_get(parser_t &parser, const wchar_t *cmd); wcstring builtin_help_get(parser_t &parser, const wchar_t *cmd);
/** Defines a function, like builtin_function. Returns 0 on success. args should NOT contain 'function' as the first argument. */
int define_function(parser_t &parser, io_streams_t &streams, const wcstring_list_t &c_args, const wcstring &contents, int definition_line_offset, wcstring *out_err);
#endif #endif

View File

@@ -79,51 +79,6 @@ static size_t get_cursor_pos()
return current_cursor_pos; return current_cursor_pos;
} }
static pthread_mutex_t transient_commandline_lock = PTHREAD_MUTEX_INITIALIZER;
static wcstring_list_t *get_transient_stack()
{
ASSERT_IS_MAIN_THREAD();
ASSERT_IS_LOCKED(transient_commandline_lock);
// A pointer is a little more efficient than an object as a static because we can elide the thread-safe initialization
static wcstring_list_t *result = NULL;
if (! result)
{
result = new wcstring_list_t();
}
return result;
}
static bool get_top_transient(wcstring *out_result)
{
ASSERT_IS_MAIN_THREAD();
bool result = false;
scoped_lock locker(transient_commandline_lock);
const wcstring_list_t *stack = get_transient_stack();
if (! stack->empty())
{
out_result->assign(stack->back());
result = true;
}
return result;
}
builtin_commandline_scoped_transient_t::builtin_commandline_scoped_transient_t(const wcstring &cmd)
{
ASSERT_IS_MAIN_THREAD();
scoped_lock locker(transient_commandline_lock);
wcstring_list_t *stack = get_transient_stack();
stack->push_back(cmd);
this->token = stack->size();
}
builtin_commandline_scoped_transient_t::~builtin_commandline_scoped_transient_t()
{
ASSERT_IS_MAIN_THREAD();
scoped_lock locker(transient_commandline_lock);
wcstring_list_t *stack = get_transient_stack();
assert(this->token == stack->size());
stack->pop_back();
}
/** /**
Replace/append/insert the selection with/at/after the specified string. Replace/append/insert the selection with/at/after the specified string.
@@ -186,43 +141,39 @@ static void replace_part(const wchar_t *begin,
static void write_part(const wchar_t *begin, static void write_part(const wchar_t *begin,
const wchar_t *end, const wchar_t *end,
int cut_at_cursor, int cut_at_cursor,
int tokenize, int tokenize)
io_streams_t &streams)
{ {
size_t pos = get_cursor_pos()-(begin-get_buffer()); wcstring out;
wchar_t *buff;
size_t pos;
pos = get_cursor_pos()-(begin-get_buffer());
if (tokenize) if (tokenize)
{ {
wchar_t *buff = wcsndup(begin, end-begin); buff = wcsndup(begin, end-begin);
// fwprintf( stderr, L"Subshell: %ls, end char %lc\n", buff, *end ); // fwprintf( stderr, L"Subshell: %ls, end char %lc\n", buff, *end );
wcstring out; out.clear();
tokenizer_t tok(buff, TOK_ACCEPT_UNFINISHED); tokenizer_t tok(buff, TOK_ACCEPT_UNFINISHED);
tok_t token; for (; tok_has_next(&tok); tok_next(&tok))
while (tok.next(&token))
{ {
if ((cut_at_cursor) && if ((cut_at_cursor) &&
(token.offset + token.text.size() >= pos)) (tok_get_pos(&tok)+wcslen(tok_last(&tok)) >= pos))
break; break;
switch (token.type) switch (tok_last_type(&tok))
{ {
case TOK_STRING: case TOK_STRING:
{ {
wcstring tmp = token.text; out.append(escape_string(tok_last(&tok), UNESCAPE_INCOMPLETE));
unescape_string_in_place(&tmp, UNESCAPE_INCOMPLETE);
out.append(tmp);
out.push_back(L'\n'); out.push_back(L'\n');
break; break;
} }
default:
{
break;
}
} }
} }
streams.out.append(out); stdout_buffer.append(out);
free(buff); free(buff);
} }
@@ -234,8 +185,9 @@ static void write_part(const wchar_t *begin,
} }
// debug( 0, L"woot2 %ls -> %ls", buff, esc ); // debug( 0, L"woot2 %ls -> %ls", buff, esc );
streams.out.append(begin, end - begin);
streams.out.append(L"\n"); stdout_buffer.append(begin, end - begin);
stdout_buffer.append(L"\n");
} }
} }
@@ -245,9 +197,9 @@ static void write_part(const wchar_t *begin,
The commandline builtin. It is used for specifying a new value for The commandline builtin. It is used for specifying a new value for
the commandline. the commandline.
*/ */
static int builtin_commandline(parser_t &parser, io_streams_t &streams, wchar_t **argv) static int builtin_commandline(parser_t &parser, wchar_t **argv)
{ {
wgetopter_t w;
int buffer_part=0; int buffer_part=0;
int cut_at_cursor=0; int cut_at_cursor=0;
@@ -255,24 +207,18 @@ static int builtin_commandline(parser_t &parser, io_streams_t &streams, wchar_t
int append_mode=0; int append_mode=0;
int function_mode = 0; int function_mode = 0;
int selection_mode = 0;
int tokenize = 0; int tokenize = 0;
int cursor_mode = 0; int cursor_mode = 0;
int line_mode = 0; int line_mode = 0;
int search_mode = 0; int search_mode = 0;
int paging_mode = 0; const wchar_t *begin, *end;
const wchar_t *begin = NULL, *end = NULL;
current_buffer = (wchar_t *)builtin_complete_get_temporary_buffer();
scoped_push<const wchar_t *> saved_current_buffer(&current_buffer); if (current_buffer)
scoped_push<size_t> saved_current_cursor_pos(&current_cursor_pos);
wcstring transient_commandline;
if (get_top_transient(&transient_commandline))
{ {
current_buffer = transient_commandline.c_str(); current_cursor_pos = wcslen(current_buffer);
current_cursor_pos = transient_commandline.size();
} }
else else
{ {
@@ -292,46 +238,92 @@ static int builtin_commandline(parser_t &parser, io_streams_t &streams, wchar_t
return 1; return 1;
} }
streams.err.append(argv[0]); stderr_buffer.append(argv[0]);
streams.err.append(L": Can not set commandline in non-interactive mode\n"); stderr_buffer.append(L": Can not set commandline in non-interactive mode\n");
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
w.woptind=0; woptind=0;
while (1) while (1)
{ {
static const struct woption static const struct woption
long_options[] = long_options[] =
{ {
{ L"append", no_argument, 0, 'a' }, {
{ L"insert", no_argument, 0, 'i' }, L"append", no_argument, 0, 'a'
{ L"replace", no_argument, 0, 'r' }, }
{ L"current-job", no_argument, 0, 'j' }, ,
{ L"current-process", no_argument, 0, 'p' }, {
{ L"current-token", no_argument, 0, 't' }, L"insert", no_argument, 0, 'i'
{ L"current-buffer", no_argument, 0, 'b' }, }
{ L"cut-at-cursor", no_argument, 0, 'c' }, ,
{ L"function", no_argument, 0, 'f' }, {
{ L"tokenize", no_argument, 0, 'o' }, L"replace", no_argument, 0, 'r'
{ L"help", no_argument, 0, 'h' }, }
{ L"input", required_argument, 0, 'I' }, ,
{ L"cursor", no_argument, 0, 'C' }, {
{ L"line", no_argument, 0, 'L' }, L"current-job", no_argument, 0, 'j'
{ L"search-mode", no_argument, 0, 'S' }, }
{ L"selection", no_argument, 0, 's' }, ,
{ L"paging-mode", no_argument, 0, 'P' }, {
{ 0, 0, 0, 0 } L"current-process", no_argument, 0, 'p'
}; }
,
{
L"current-token", no_argument, 0, 't'
}
,
{
L"current-buffer", no_argument, 0, 'b'
}
,
{
L"cut-at-cursor", no_argument, 0, 'c'
}
,
{
L"function", no_argument, 0, 'f'
}
,
{
L"tokenize", no_argument, 0, 'o'
}
,
{
L"help", no_argument, 0, 'h'
}
,
{
L"input", required_argument, 0, 'I'
}
,
{
L"cursor", no_argument, 0, 'C'
}
,
{
L"line", no_argument, 0, 'L'
}
,
{
L"search-mode", no_argument, 0, 'S'
}
,
{
0, 0, 0, 0
}
}
;
int opt_index = 0; int opt_index = 0;
int opt = w.wgetopt_long(argc, int opt = wgetopt_long(argc,
argv, argv,
L"abijpctwforhI:CLSsP", L"abijpctwforhI:CLS",
long_options, long_options,
&opt_index); &opt_index);
if (opt == -1) if (opt == -1)
break; break;
@@ -340,10 +332,11 @@ static int builtin_commandline(parser_t &parser, io_streams_t &streams, wchar_t
case 0: case 0:
if (long_options[opt_index].flag != 0) if (long_options[opt_index].flag != 0)
break; break;
streams.err.append_format(BUILTIN_ERR_UNKNOWN, append_format(stderr_buffer,
BUILTIN_ERR_UNKNOWN,
argv[0], argv[0],
long_options[opt_index].name); long_options[opt_index].name);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
@@ -389,8 +382,8 @@ static int builtin_commandline(parser_t &parser, io_streams_t &streams, wchar_t
break; break;
case 'I': case 'I':
current_buffer = w.woptarg; current_buffer = woptarg;
current_cursor_pos = wcslen(w.woptarg); current_cursor_pos = wcslen(woptarg);
break; break;
case 'C': case 'C':
@@ -405,20 +398,12 @@ static int builtin_commandline(parser_t &parser, io_streams_t &streams, wchar_t
search_mode = 1; search_mode = 1;
break; break;
case 's':
selection_mode = 1;
break;
case 'P':
paging_mode = 1;
break;
case 'h': case 'h':
builtin_print_help(parser, streams, argv[0], streams.out); builtin_print_help(parser, argv[0], stdout_buffer);
return 0; return 0;
case L'?': case L'?':
builtin_unknown_option(parser, streams, argv[0], argv[w.woptind-1]); builtin_unknown_option(parser, argv[0], argv[woptind-1]);
return 1; return 1;
} }
} }
@@ -430,42 +415,45 @@ static int builtin_commandline(parser_t &parser, io_streams_t &streams, wchar_t
/* /*
Check for invalid switch combinations Check for invalid switch combinations
*/ */
if (buffer_part || cut_at_cursor || append_mode || tokenize || cursor_mode || line_mode || search_mode || paging_mode) if (buffer_part || cut_at_cursor || append_mode || tokenize || cursor_mode || line_mode || search_mode)
{ {
streams.err.append_format(BUILTIN_ERR_COMBO, append_format(stderr_buffer,
BUILTIN_ERR_COMBO,
argv[0]); argv[0]);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
if (argc == w.woptind) if (argc == woptind)
{ {
streams.err.append_format(BUILTIN_ERR_MISSING, append_format(stderr_buffer,
BUILTIN_ERR_MISSING,
argv[0]); argv[0]);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
for (i=w.woptind; i<argc; i++) for (i=woptind; i<argc; i++)
{ {
wchar_t c = input_function_get_code(argv[i]); wchar_t c = input_function_get_code(argv[i]);
if (c != INPUT_CODE_NONE) if (c != (wchar_t)(-1))
{ {
/* /*
input_unreadch inserts the specified keypress or input_unreadch inserts the specified keypress or
readline function at the back of the queue of unused readline function at the top of the stack of unused
keypresses keypresses
*/ */
input_queue_ch(c); input_unreadch(c);
} }
else else
{ {
streams.err.append_format(_(L"%ls: Unknown input function '%ls'\n"), append_format(stderr_buffer,
_(L"%ls: Unknown input function '%ls'\n"),
argv[0], argv[0],
argv[i]); argv[i]);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
} }
@@ -473,58 +461,51 @@ static int builtin_commandline(parser_t &parser, io_streams_t &streams, wchar_t
return 0; return 0;
} }
if (selection_mode)
{
size_t start, len;
const wchar_t *buffer = reader_get_buffer();
if (reader_get_selection(&start, &len))
{
streams.out.append(buffer + start, len);
}
return 0;
}
/* /*
Check for invalid switch combinations Check for invalid switch combinations
*/ */
if ((search_mode || line_mode || cursor_mode || paging_mode) && (argc-w.woptind > 1)) if ((search_mode || line_mode || cursor_mode) && (argc-woptind > 1))
{ {
streams.err.append_format(argv[0], append_format(stderr_buffer,
argv[0],
L": Too many arguments\n", L": Too many arguments\n",
NULL); NULL);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
if ((buffer_part || tokenize || cut_at_cursor) && (cursor_mode || line_mode || search_mode || paging_mode)) if ((buffer_part || tokenize || cut_at_cursor) && (cursor_mode || line_mode || search_mode))
{ {
streams.err.append_format(BUILTIN_ERR_COMBO, append_format(stderr_buffer,
BUILTIN_ERR_COMBO,
argv[0]); argv[0]);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
if ((tokenize || cut_at_cursor) && (argc-w.woptind)) if ((tokenize || cut_at_cursor) && (argc-woptind))
{ {
streams.err.append_format(BUILTIN_ERR_COMBO2, append_format(stderr_buffer,
BUILTIN_ERR_COMBO2,
argv[0], argv[0],
L"--cut-at-cursor and --tokenize can not be used when setting the commandline"); L"--cut-at-cursor and --tokenize can not be used when setting the commandline");
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
if (append_mode && !(argc-w.woptind)) if (append_mode && !(argc-woptind))
{ {
streams.err.append_format(BUILTIN_ERR_COMBO2, append_format(stderr_buffer,
BUILTIN_ERR_COMBO2,
argv[0], argv[0],
L"insertion mode switches can not be used when not in insertion mode"); L"insertion mode switches can not be used when not in insertion mode");
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
@@ -543,19 +524,20 @@ static int builtin_commandline(parser_t &parser, io_streams_t &streams, wchar_t
if (cursor_mode) if (cursor_mode)
{ {
if (argc-w.woptind) if (argc-woptind)
{ {
wchar_t *endptr; wchar_t *endptr;
long new_pos; long new_pos;
errno = 0; errno = 0;
new_pos = wcstol(argv[w.woptind], &endptr, 10); new_pos = wcstol(argv[woptind], &endptr, 10);
if (*endptr || errno) if (*endptr || errno)
{ {
streams.err.append_format(BUILTIN_ERR_NOT_NUMBER, append_format(stderr_buffer,
BUILTIN_ERR_NOT_NUMBER,
argv[0], argv[0],
argv[w.woptind]); argv[woptind]);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
} }
current_buffer = reader_get_buffer(); current_buffer = reader_get_buffer();
@@ -565,7 +547,7 @@ static int builtin_commandline(parser_t &parser, io_streams_t &streams, wchar_t
} }
else else
{ {
streams.out.append_format( L"%lu\n", (unsigned long)reader_get_cursor_pos()); append_format(stdout_buffer, L"%lu\n", (unsigned long)reader_get_cursor_pos());
return 0; return 0;
} }
@@ -575,19 +557,14 @@ static int builtin_commandline(parser_t &parser, io_streams_t &streams, wchar_t
{ {
size_t pos = reader_get_cursor_pos(); size_t pos = reader_get_cursor_pos();
const wchar_t *buff = reader_get_buffer(); const wchar_t *buff = reader_get_buffer();
streams.out.append_format( L"%lu\n", (unsigned long)parse_util_lineno(buff, pos)); append_format(stdout_buffer, L"%lu\n", (unsigned long)parse_util_lineno(buff, pos));
return 0; return 0;
} }
if (search_mode) if (search_mode)
{ {
return ! reader_search_mode(); return !reader_search_mode();
}
if (paging_mode)
{
return ! reader_has_pager_contents();
} }
@@ -630,26 +607,26 @@ static int builtin_commandline(parser_t &parser, io_streams_t &streams, wchar_t
} }
switch (argc-w.woptind) switch (argc-woptind)
{ {
case 0: case 0:
{ {
write_part(begin, end, cut_at_cursor, tokenize, streams); write_part(begin, end, cut_at_cursor, tokenize);
break; break;
} }
case 1: case 1:
{ {
replace_part(begin, end, argv[w.woptind], append_mode); replace_part(begin, end, argv[woptind], append_mode);
break; break;
} }
default: default:
{ {
wcstring sb = argv[w.woptind]; wcstring sb = argv[woptind];
int i; int i;
for (i=w.woptind+1; i<argc; i++) for (i=woptind+1; i<argc; i++)
{ {
sb.push_back(L'\n'); sb.push_back(L'\n');
sb.append(argv[i]); sb.append(argv[i]);

View File

@@ -24,6 +24,12 @@ Functions used for implementing the complete builtin.
#include "parser.h" #include "parser.h"
#include "reader.h" #include "reader.h"
/**
Internal storage for the builtin_complete_get_temporary_buffer() function.
*/
static const wchar_t *temporary_buffer;
/* /*
builtin_complete_* are a set of rather silly looping functions that builtin_complete_* are a set of rather silly looping functions that
make sure that all the proper combinations of complete_add or make sure that all the proper combinations of complete_add or
@@ -54,8 +60,9 @@ static void builtin_complete_add2(const wchar_t *cmd,
{ {
complete_add(cmd, complete_add(cmd,
cmd_type, cmd_type,
wcstring(1, *s), *s,
option_type_short, 0,
0,
result_mode, result_mode,
condition, condition,
comp, comp,
@@ -67,8 +74,9 @@ static void builtin_complete_add2(const wchar_t *cmd,
{ {
complete_add(cmd, complete_add(cmd,
cmd_type, cmd_type,
gnu_opt.at(i), 0,
option_type_double_long, gnu_opt.at(i).c_str(),
0,
result_mode, result_mode,
condition, condition,
comp, comp,
@@ -80,8 +88,9 @@ static void builtin_complete_add2(const wchar_t *cmd,
{ {
complete_add(cmd, complete_add(cmd,
cmd_type, cmd_type,
old_opt.at(i), 0,
option_type_single_long, old_opt.at(i).c_str(),
1,
result_mode, result_mode,
condition, condition,
comp, comp,
@@ -93,8 +102,9 @@ static void builtin_complete_add2(const wchar_t *cmd,
{ {
complete_add(cmd, complete_add(cmd,
cmd_type, cmd_type,
wcstring(), 0,
option_type_args_only, 0,
0,
result_mode, result_mode,
condition, condition,
comp, comp,
@@ -163,72 +173,124 @@ static void builtin_complete_add(const wcstring_list_t &cmd,
} }
} }
static void builtin_complete_remove_cmd(const wcstring &cmd, /**
int cmd_type, Silly function
const wchar_t *short_opt, */
const wcstring_list_t &gnu_opt, static void builtin_complete_remove3(const wchar_t *cmd,
const wcstring_list_t &old_opt) int cmd_type,
wchar_t short_opt,
const wcstring_list_t &long_opt)
{ {
bool removed = false; for (size_t i=0; i<long_opt.size(); i++)
size_t i;
for (i=0; short_opt[i] != L'\0'; i++)
{ {
complete_remove(cmd, cmd_type, wcstring(1, short_opt[i]), option_type_short); complete_remove(cmd,
removed = true; cmd_type,
} short_opt,
long_opt.at(i).c_str());
for (i=0; i < old_opt.size(); i++)
{
complete_remove(cmd, cmd_type, old_opt.at(i), option_type_single_long);
removed = true;
}
for (i=0; i < gnu_opt.size(); i++)
{
complete_remove(cmd, cmd_type, gnu_opt.at(i), option_type_double_long);
removed = true;
}
if (! removed)
{
// This means that all loops were empty
complete_remove_all(cmd, cmd_type);
} }
} }
/**
Silly function
*/
static void builtin_complete_remove2(const wchar_t *cmd,
int cmd_type,
const wchar_t *short_opt,
const wcstring_list_t &gnu_opt,
const wcstring_list_t &old_opt)
{
const wchar_t *s = (wchar_t *)short_opt;
if (*s)
{
for (; *s; s++)
{
if (old_opt.empty() && gnu_opt.empty())
{
complete_remove(cmd,
cmd_type,
*s,
0);
}
else
{
builtin_complete_remove3(cmd,
cmd_type,
*s,
gnu_opt);
builtin_complete_remove3(cmd,
cmd_type,
*s,
old_opt);
}
}
}
else
{
builtin_complete_remove3(cmd,
cmd_type,
0,
gnu_opt);
builtin_complete_remove3(cmd,
cmd_type,
0,
old_opt);
}
}
/**
Silly function
*/
static void builtin_complete_remove(const wcstring_list_t &cmd, static void builtin_complete_remove(const wcstring_list_t &cmd,
const wcstring_list_t &path, const wcstring_list_t &path,
const wchar_t *short_opt, const wchar_t *short_opt,
const wcstring_list_t &gnu_opt, const wcstring_list_t &gnu_opt,
const wcstring_list_t &old_opt) const wcstring_list_t &old_opt)
{ {
for (size_t i=0; i<cmd.size(); i++) for (size_t i=0; i<cmd.size(); i++)
{ {
builtin_complete_remove_cmd(cmd.at(i), COMMAND, short_opt, gnu_opt, old_opt); builtin_complete_remove2(cmd.at(i).c_str(),
COMMAND,
short_opt,
gnu_opt,
old_opt);
} }
for (size_t i=0; i<path.size(); i++) for (size_t i=0; i<path.size(); i++)
{ {
builtin_complete_remove_cmd(path.at(i), PATH, short_opt, gnu_opt, old_opt); builtin_complete_remove2(path.at(i).c_str(),
PATH,
short_opt,
gnu_opt,
old_opt);
} }
} }
const wchar_t *builtin_complete_get_temporary_buffer()
{
ASSERT_IS_MAIN_THREAD();
return temporary_buffer;
}
/** /**
The complete builtin. Used for specifying programmable The complete builtin. Used for specifying programmable
tab-completions. Calls the functions in complete.c for any heavy tab-completions. Calls the functions in complete.c for any heavy
lifting. Defined in builtin_complete.c lifting. Defined in builtin_complete.c
*/ */
static int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **argv) static int builtin_complete(parser_t &parser, wchar_t **argv)
{ {
ASSERT_IS_MAIN_THREAD(); ASSERT_IS_MAIN_THREAD();
wgetopter_t w;
bool res=false; bool res=false;
int argc=0; int argc=0;
int result_mode=SHARED; int result_mode=SHARED;
int remove = 0; int remove = 0;
int authoritative = -1; int authoritative = -1;
int flags = COMPLETE_AUTO_SPACE;
wcstring short_opt; wcstring short_opt;
wcstring_list_t gnu_opt, old_opt; wcstring_list_t gnu_opt, old_opt;
@@ -239,46 +301,95 @@ static int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **a
wcstring_list_t cmd; wcstring_list_t cmd;
wcstring_list_t path; wcstring_list_t path;
wcstring_list_t wrap_targets;
static int recursion_level=0; static int recursion_level=0;
argc = builtin_count_args(argv); argc = builtin_count_args(argv);
w.woptind=0; woptind=0;
while (! res) while (! res)
{ {
static const struct woption static const struct woption
long_options[] = long_options[] =
{ {
{ L"exclusive", no_argument, 0, 'x' }, {
{ L"no-files", no_argument, 0, 'f' }, L"exclusive", no_argument, 0, 'x'
{ L"require-parameter", no_argument, 0, 'r' }, }
{ L"path", required_argument, 0, 'p' }, ,
{ L"command", required_argument, 0, 'c' }, {
{ L"short-option", required_argument, 0, 's' }, L"no-files", no_argument, 0, 'f'
{ L"long-option", required_argument, 0, 'l' }, }
{ L"old-option", required_argument, 0, 'o' }, ,
{ L"description", required_argument, 0, 'd' }, {
{ L"arguments", required_argument, 0, 'a' }, L"require-parameter", no_argument, 0, 'r'
{ L"erase", no_argument, 0, 'e' }, }
{ L"unauthoritative", no_argument, 0, 'u' }, ,
{ L"authoritative", no_argument, 0, 'A' }, {
{ L"condition", required_argument, 0, 'n' }, L"path", required_argument, 0, 'p'
{ L"wraps", required_argument, 0, 'w' }, }
{ L"do-complete", optional_argument, 0, 'C' }, ,
{ L"help", no_argument, 0, 'h' }, {
{ 0, 0, 0, 0 } L"command", required_argument, 0, 'c'
}; }
,
{
L"short-option", required_argument, 0, 's'
}
,
{
L"long-option", required_argument, 0, 'l'
}
,
{
L"old-option", required_argument, 0, 'o'
}
,
{
L"description", required_argument, 0, 'd'
}
,
{
L"arguments", required_argument, 0, 'a'
}
,
{
L"erase", no_argument, 0, 'e'
}
,
{
L"unauthoritative", no_argument, 0, 'u'
}
,
{
L"authoritative", no_argument, 0, 'A'
}
,
{
L"condition", required_argument, 0, 'n'
}
,
{
L"do-complete", optional_argument, 0, 'C'
}
,
{
L"help", no_argument, 0, 'h'
}
,
{
0, 0, 0, 0
}
}
;
int opt_index = 0; int opt_index = 0;
int opt = w.wgetopt_long(argc, int opt = wgetopt_long(argc,
argv, argv,
L"a:c:p:s:l:o:d:frxeuAn:C::w:h", L"a:c:p:s:l:o:d:frxeuAn:C::h",
long_options, long_options,
&opt_index); &opt_index);
if (opt == -1) if (opt == -1)
break; break;
@@ -287,10 +398,11 @@ static int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **a
case 0: case 0:
if (long_options[opt_index].flag != 0) if (long_options[opt_index].flag != 0)
break; break;
streams.err.append_format(BUILTIN_ERR_UNKNOWN, append_format(stderr_buffer,
BUILTIN_ERR_UNKNOWN,
argv[0], argv[0],
long_options[opt_index].name); long_options[opt_index].name);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
res = true; res = true;
@@ -311,8 +423,8 @@ static int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **a
case 'p': case 'p':
case 'c': case 'c':
{ {
wcstring tmp; wcstring tmp = woptarg;
if (unescape_string(w.woptarg, &tmp, UNESCAPE_SPECIAL)) if (unescape_string(tmp, 1))
{ {
if (opt=='p') if (opt=='p')
path.push_back(tmp); path.push_back(tmp);
@@ -321,14 +433,14 @@ static int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **a
} }
else else
{ {
streams.err.append_format(L"%ls: Invalid token '%ls'\n", argv[0], w.woptarg); append_format(stderr_buffer, L"%ls: Invalid token '%ls'\n", argv[0], woptarg);
res = true; res = true;
} }
break; break;
} }
case 'd': case 'd':
desc = w.woptarg; desc = woptarg;
break; break;
case 'u': case 'u':
@@ -340,19 +452,19 @@ static int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **a
break; break;
case 's': case 's':
short_opt.append(w.woptarg); short_opt.append(woptarg);
break; break;
case 'l': case 'l':
gnu_opt.push_back(w.woptarg); gnu_opt.push_back(woptarg);
break; break;
case 'o': case 'o':
old_opt.push_back(w.woptarg); old_opt.push_back(woptarg);
break; break;
case 'a': case 'a':
comp = w.woptarg; comp = woptarg;
break; break;
case 'e': case 'e':
@@ -360,34 +472,20 @@ static int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **a
break; break;
case 'n': case 'n':
condition = w.woptarg; condition = woptarg;
break;
case 'w':
wrap_targets.push_back(w.woptarg);
break; break;
case 'C': case 'C':
{
do_complete = true; do_complete = true;
const wchar_t *arg = w.woptarg ? w.woptarg : reader_get_buffer(); do_complete_param = woptarg ? woptarg : reader_get_buffer();
if (arg == NULL)
{
// This corresponds to using 'complete -C' in non-interactive mode
// See #2361
builtin_missing_argument(parser, streams, argv[0], argv[w.woptind-1]);
return STATUS_BUILTIN_ERROR;
}
do_complete_param = arg;
break; break;
}
case 'h': case 'h':
builtin_print_help(parser, streams, argv[0], streams.out); builtin_print_help(parser, argv[0], stdout_buffer);
return 0; return 0;
case '?': case '?':
builtin_unknown_option(parser, streams, argv[0], argv[w.woptind-1]); builtin_unknown_option(parser, argv[0], argv[woptind-1]);
res = true; res = true;
break; break;
@@ -399,18 +497,15 @@ static int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **a
{ {
if (condition && wcslen(condition)) if (condition && wcslen(condition))
{ {
const wcstring condition_string = condition; if (parser.test(condition))
parse_error_list_t errors;
if (parse_util_detect_errors(condition_string, &errors, false /* do not accept incomplete */))
{ {
streams.err.append_format(L"%ls: Condition '%ls' contained a syntax error", append_format(stderr_buffer,
L"%ls: Condition '%ls' contained a syntax error\n",
argv[0], argv[0],
condition); condition);
for (size_t i=0; i < errors.size(); i++)
{ parser.test(condition, NULL, &stderr_buffer, argv[0]);
streams.err.append_format(L"\n%s: ", argv[0]);
streams.err.append(errors.at(i).describe(condition_string));
}
res = true; res = true;
} }
} }
@@ -420,21 +515,15 @@ static int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **a
{ {
if (comp && wcslen(comp)) if (comp && wcslen(comp))
{ {
wcstring prefix; if (parser.test_args(comp, 0, 0))
if (argv[0])
{ {
prefix.append(argv[0]); append_format(stderr_buffer,
prefix.append(L": "); L"%ls: Completion '%ls' contained a syntax error\n",
}
wcstring err_text;
if (parser.detect_errors_in_argument_list(comp, &err_text, prefix.c_str()))
{
streams.err.append_format(L"%ls: Completion '%ls' contained a syntax error\n",
argv[0], argv[0],
comp); comp);
streams.err.append(err_text);
streams.err.push_back(L'\n'); parser.test_args(comp, &stderr_buffer, argv[0]);
res = true; res = true;
} }
} }
@@ -447,53 +536,55 @@ static int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **a
const wchar_t *token; const wchar_t *token;
parse_util_token_extent(do_complete_param.c_str(), do_complete_param.size(), &token, 0, 0, 0); parse_util_token_extent(do_complete_param.c_str(), do_complete_param.size(), &token, 0, 0, 0);
/* Create a scoped transient command line, so that bulitin_commandline will see our argument, not the reader buffer */ const wchar_t *prev_temporary_buffer = temporary_buffer;
builtin_commandline_scoped_transient_t temp_buffer(do_complete_param); temporary_buffer = do_complete_param.c_str();
if (recursion_level < 1) if (recursion_level < 1)
{ {
recursion_level++; recursion_level++;
std::vector<completion_t> comp; std::vector<completion_t> comp;
complete(do_complete_param, &comp, COMPLETION_REQUEST_DEFAULT, env_vars_snapshot_t::current()); complete(do_complete_param, comp, COMPLETION_REQUEST_DEFAULT);
for (size_t i=0; i< comp.size() ; i++) for (size_t i=0; i< comp.size() ; i++)
{ {
const completion_t &next = comp.at(i); const completion_t &next = comp.at(i);
/* Make a fake commandline, and then apply the completion to it. */ const wchar_t *prepend;
const wcstring faux_cmdline = token;
size_t tmp_cursor = faux_cmdline.size();
wcstring faux_cmdline_with_completion = completion_apply_to_command_line(next.completion, next.flags, faux_cmdline, &tmp_cursor, false);
/* completion_apply_to_command_line will append a space unless COMPLETE_NO_SPACE is set. We don't want to set COMPLETE_NO_SPACE because that won't close quotes. What we want is to close the quote, but not append the space. So we just look for the space and clear it. */ if (next.flags & COMPLETE_REPLACES_TOKEN)
if (!(next.flags & COMPLETE_NO_SPACE) && string_suffixes_string(L" ", faux_cmdline_with_completion))
{ {
faux_cmdline_with_completion.resize(faux_cmdline_with_completion.size() - 1); prepend = L"";
}
else
{
prepend = token;
} }
/* The input data is meant to be something like you would have on the command line, e.g. includes backslashes. The output should be raw, i.e. unescaped. So we need to unescape the command line. See #1127 */
unescape_string_in_place(&faux_cmdline_with_completion, UNESCAPE_DEFAULT);
streams.out.append(faux_cmdline_with_completion);
/* Append any description */ if (!(next.description).empty())
if (! next.description.empty())
{ {
streams.out.push_back(L'\t'); append_format(stdout_buffer, L"%ls%ls\t%ls\n", prepend, next.completion.c_str(), next.description.c_str());
streams.out.append(next.description); }
else
{
append_format(stdout_buffer, L"%ls%ls\n", prepend, next.completion.c_str());
} }
streams.out.push_back(L'\n');
} }
recursion_level--; recursion_level--;
} }
temporary_buffer = prev_temporary_buffer;
} }
else if (w.woptind != argc) else if (woptind != argc)
{ {
streams.err.append_format(_(L"%ls: Too many arguments\n"), append_format(stderr_buffer,
_(L"%ls: Too many arguments\n"),
argv[0]); argv[0]);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
res = true; res = true;
} }
@@ -501,12 +592,10 @@ static int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **a
{ {
/* No arguments specified, meaning we print the definitions of /* No arguments specified, meaning we print the definitions of
* all specified completions to stdout.*/ * all specified completions to stdout.*/
streams.out.append(complete_print()); complete_print(stdout_buffer);
} }
else else
{ {
int flags = COMPLETE_AUTO_SPACE;
if (remove) if (remove)
{ {
builtin_complete_remove(cmd, builtin_complete_remove(cmd,
@@ -514,7 +603,6 @@ static int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **a
short_opt.c_str(), short_opt.c_str(),
gnu_opt, gnu_opt,
old_opt); old_opt);
} }
else else
{ {
@@ -530,18 +618,7 @@ static int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **a
desc, desc,
flags); flags);
} }
// Handle wrap targets (probably empty)
// We only wrap commands, not paths
for (size_t w=0; w < wrap_targets.size(); w++)
{
const wcstring &wrap_target = wrap_targets.at(w);
for (size_t i=0; i < cmd.size(); i++)
{
(remove ? complete_remove_wrapper : complete_add_wrapper)(cmd.at(i), wrap_target);
}
}
} }
} }

View File

@@ -71,7 +71,7 @@ static int cpu_use(const job_t *j)
/** /**
Print information about the specified job Print information about the specified job
*/ */
static void builtin_jobs_print(const job_t *j, int mode, int header, io_streams_t &streams) static void builtin_jobs_print(const job_t *j, int mode, int header)
{ {
process_t *p; process_t *p;
switch (mode) switch (mode)
@@ -84,22 +84,22 @@ static void builtin_jobs_print(const job_t *j, int mode, int header, io_streams_
/* /*
Print table header before first job Print table header before first job
*/ */
streams.out.append(_(L"Job\tGroup\t")); stdout_buffer.append(_(L"Job\tGroup\t"));
#ifdef HAVE__PROC_SELF_STAT #ifdef HAVE__PROC_SELF_STAT
streams.out.append(_(L"CPU\t")); stdout_buffer.append(_(L"CPU\t"));
#endif #endif
streams.out.append(_(L"State\tCommand\n")); stdout_buffer.append(_(L"State\tCommand\n"));
} }
streams.out.append_format( L"%d\t%d\t", j->job_id, j->pgid); append_format(stdout_buffer, L"%d\t%d\t", j->job_id, j->pgid);
#ifdef HAVE__PROC_SELF_STAT #ifdef HAVE__PROC_SELF_STAT
streams.out.append_format( L"%d%%\t", cpu_use(j)); append_format(stdout_buffer, L"%d%%\t", cpu_use(j));
#endif #endif
streams.out.append(job_is_stopped(j)?_(L"stopped"):_(L"running")); stdout_buffer.append(job_is_stopped(j)?_(L"stopped"):_(L"running"));
streams.out.append(L"\t"); stdout_buffer.append(L"\t");
streams.out.append(j->command_wcstr()); stdout_buffer.append(j->command_wcstr());
streams.out.append(L"\n"); stdout_buffer.append(L"\n");
break; break;
} }
@@ -110,9 +110,9 @@ static void builtin_jobs_print(const job_t *j, int mode, int header, io_streams_
/* /*
Print table header before first job Print table header before first job
*/ */
streams.out.append(_(L"Group\n")); stdout_buffer.append(_(L"Group\n"));
} }
streams.out.append_format( L"%d\n", j->pgid); append_format(stdout_buffer, L"%d\n", j->pgid);
break; break;
} }
@@ -123,12 +123,12 @@ static void builtin_jobs_print(const job_t *j, int mode, int header, io_streams_
/* /*
Print table header before first job Print table header before first job
*/ */
streams.out.append(_(L"Process\n")); stdout_buffer.append(_(L"Procces\n"));
} }
for (p=j->first_process; p; p=p->next) for (p=j->first_process; p; p=p->next)
{ {
streams.out.append_format( L"%d\n", p->pid); append_format(stdout_buffer, L"%d\n", p->pid);
} }
break; break;
} }
@@ -140,12 +140,12 @@ static void builtin_jobs_print(const job_t *j, int mode, int header, io_streams_
/* /*
Print table header before first job Print table header before first job
*/ */
streams.out.append(_(L"Command\n")); stdout_buffer.append(_(L"Command\n"));
} }
for (p=j->first_process; p; p=p->next) for (p=j->first_process; p; p=p->next)
{ {
streams.out.append_format( L"%ls\n", p->argv0()); append_format(stdout_buffer, L"%ls\n", p->argv0());
} }
break; break;
} }
@@ -158,16 +158,16 @@ static void builtin_jobs_print(const job_t *j, int mode, int header, io_streams_
/** /**
The jobs builtin. Used fopr printing running jobs. Defined in builtin_jobs.c. The jobs builtin. Used fopr printing running jobs. Defined in builtin_jobs.c.
*/ */
static int builtin_jobs(parser_t &parser, io_streams_t &streams, wchar_t **argv) static int builtin_jobs(parser_t &parser, wchar_t **argv)
{ {
wgetopter_t w;
int argc=0; int argc=0;
int found=0; int found=0;
int mode=JOBS_DEFAULT; int mode=JOBS_DEFAULT;
int print_last = 0; int print_last = 0;
const job_t *j;
argc = builtin_count_args(argv); argc = builtin_count_args(argv);
w.woptind=0; woptind=0;
while (1) while (1)
{ {
@@ -202,11 +202,11 @@ static int builtin_jobs(parser_t &parser, io_streams_t &streams, wchar_t **argv)
int opt_index = 0; int opt_index = 0;
int opt = w.wgetopt_long(argc, int opt = wgetopt_long(argc,
argv, argv,
L"pclgh", L"pclgh",
long_options, long_options,
&opt_index); &opt_index);
if (opt == -1) if (opt == -1)
break; break;
@@ -215,11 +215,12 @@ static int builtin_jobs(parser_t &parser, io_streams_t &streams, wchar_t **argv)
case 0: case 0:
if (long_options[opt_index].flag != 0) if (long_options[opt_index].flag != 0)
break; break;
streams.err.append_format(BUILTIN_ERR_UNKNOWN, append_format(stderr_buffer,
BUILTIN_ERR_UNKNOWN,
argv[0], argv[0],
long_options[opt_index].name); long_options[opt_index].name);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
@@ -244,16 +245,25 @@ static int builtin_jobs(parser_t &parser, io_streams_t &streams, wchar_t **argv)
} }
case 'h': case 'h':
builtin_print_help(parser, streams, argv[0], streams.out); builtin_print_help(parser, argv[0], stdout_buffer);
return 0; return 0;
case '?': case '?':
builtin_unknown_option(parser, streams, argv[0], argv[w.woptind-1]); builtin_unknown_option(parser, argv[0], argv[woptind-1]);
return 1; return 1;
} }
} }
/*
Do not babble if not interactive
*/
if (builtin_out_redirect)
{
found=1;
}
if (print_last) if (print_last)
{ {
/* /*
@@ -266,7 +276,7 @@ static int builtin_jobs(parser_t &parser, io_streams_t &streams, wchar_t **argv)
if ((j->flags & JOB_CONSTRUCTED) && !job_is_completed(j)) if ((j->flags & JOB_CONSTRUCTED) && !job_is_completed(j))
{ {
builtin_jobs_print(j, mode, !streams.out_is_redirected, streams); builtin_jobs_print(j, mode, !found);
return 0; return 0;
} }
} }
@@ -274,11 +284,13 @@ static int builtin_jobs(parser_t &parser, io_streams_t &streams, wchar_t **argv)
} }
else else
{ {
if (w.woptind < argc) if (woptind < argc)
{ {
int i; int i;
for (i=w.woptind; i<argc; i++) found = 1;
for (i=woptind; i<argc; i++)
{ {
int pid; int pid;
wchar_t *end; wchar_t *end;
@@ -286,22 +298,23 @@ static int builtin_jobs(parser_t &parser, io_streams_t &streams, wchar_t **argv)
pid=fish_wcstoi(argv[i], &end, 10); pid=fish_wcstoi(argv[i], &end, 10);
if (errno || *end) if (errno || *end)
{ {
streams.err.append_format(_(L"%ls: '%ls' is not a job\n"), append_format(stderr_buffer,
_(L"%ls: '%ls' is not a job\n"),
argv[0], argv[0],
argv[i]); argv[i]);
return 1; return 1;
} }
const job_t *j = job_get_from_pid(pid); j = job_get_from_pid(pid);
if (j && !job_is_completed(j)) if (j && !job_is_completed(j))
{ {
builtin_jobs_print(j, mode, false, streams); builtin_jobs_print(j, mode, !found);
found = 1;
} }
else else
{ {
streams.err.append_format(_(L"%ls: No suitable job: %d\n"), append_format(stderr_buffer,
_(L"%ls: No suitable job: %d\n"),
argv[0], argv[0],
pid); pid);
return 1; return 1;
@@ -319,7 +332,7 @@ static int builtin_jobs(parser_t &parser, io_streams_t &streams, wchar_t **argv)
*/ */
if ((j->flags & JOB_CONSTRUCTED) && !job_is_completed(j)) if ((j->flags & JOB_CONSTRUCTED) && !job_is_completed(j))
{ {
builtin_jobs_print(j, mode, !streams.out_is_redirected, streams); builtin_jobs_print(j, mode, !found);
found = 1; found = 1;
} }
} }
@@ -328,16 +341,9 @@ static int builtin_jobs(parser_t &parser, io_streams_t &streams, wchar_t **argv)
if (!found) if (!found)
{ {
/* append_format(stdout_buffer,
Do not babble if not interactive _(L"%ls: There are no jobs\n"),
*/ argv[0]);
if (!streams.out_is_redirected)
{
streams.out.append_format(
_(L"%ls: There are no jobs\n"),
argv[0]);
}
return 1;
} }
return 0; return 0;

View File

@@ -26,7 +26,6 @@
\a = alert (bell) \a = alert (bell)
\b = backspace \b = backspace
\c = produce no further output \c = produce no further output
\e = escape
\f = form feed \f = form feed
\n = new line \n = new line
\r = carriage return \r = carriage return
@@ -57,16 +56,13 @@
struct builtin_printf_state_t struct builtin_printf_state_t
{ {
/* Out and err streams. Note this is a captured reference! */
io_streams_t &streams;
/* The status of the operation */ /* The status of the operation */
int exit_code; int exit_code;
/* Whether we should stop outputting. This gets set in the case of an error, and also with the \c escape. */ /* Whether we should stop outputting. This gets set in the case of an error, and also with the \c escape. */
bool early_exit; bool early_exit;
explicit builtin_printf_state_t(io_streams_t &s) : streams(s), exit_code(0), early_exit(false) builtin_printf_state_t() : exit_code(0), early_exit(false)
{ {
} }
@@ -198,6 +194,11 @@ double C_STRTOD(wchar_t const *nptr, wchar_t **endptr)
return r; return r;
} }
static inline unsigned wchar_t to_uwchar_t(wchar_t ch)
{
return ch;
}
void builtin_printf_state_t::fatal_error(const wchar_t *fmt, ...) void builtin_printf_state_t::fatal_error(const wchar_t *fmt, ...)
{ {
// Don't error twice // Don't error twice
@@ -208,9 +209,9 @@ void builtin_printf_state_t::fatal_error(const wchar_t *fmt, ...)
va_start(va, fmt); va_start(va, fmt);
wcstring errstr = vformat_string(fmt, va); wcstring errstr = vformat_string(fmt, va);
va_end(va); va_end(va);
streams.err.append(errstr); stderr_buffer.append(errstr);
if (! string_suffixes_string(L"\n", errstr)) if (! string_suffixes_string(L"\n", errstr))
streams.err.push_back(L'\n'); stderr_buffer.push_back(L'\n');
this->exit_code = STATUS_BUILTIN_ERROR; this->exit_code = STATUS_BUILTIN_ERROR;
this->early_exit = true; this->early_exit = true;
@@ -222,7 +223,7 @@ void builtin_printf_state_t::append_output(wchar_t c)
if (early_exit) if (early_exit)
return; return;
streams.out.push_back(c); stdout_buffer.push_back(c);
} }
void builtin_printf_state_t::append_output(const wchar_t *c) void builtin_printf_state_t::append_output(const wchar_t *c)
@@ -231,7 +232,7 @@ void builtin_printf_state_t::append_output(const wchar_t *c)
if (early_exit) if (early_exit)
return; return;
streams.out.append(c); stdout_buffer.append(c);
} }
void builtin_printf_state_t::append_format_output(const wchar_t *fmt, ...) void builtin_printf_state_t::append_format_output(const wchar_t *fmt, ...)
@@ -242,9 +243,8 @@ void builtin_printf_state_t::append_format_output(const wchar_t *fmt, ...)
va_list va; va_list va;
va_start(va, fmt); va_start(va, fmt);
wcstring tmp = vformat_string(fmt, va); append_formatv(stdout_buffer, fmt, va);
va_end(va); va_end(va);
streams.out.append(tmp);
} }
@@ -291,7 +291,7 @@ static T string_to_scalar_type(const wchar_t *s, builtin_printf_state_t *state)
T val; T val;
if (*s == L'\"' || *s == L'\'') if (*s == L'\"' || *s == L'\'')
{ {
wchar_t ch = *++s; unsigned wchar_t ch = *++s;
val = ch; val = ch;
} }
else else
@@ -319,9 +319,6 @@ void builtin_printf_state_t::print_esc_char(wchar_t c)
case L'c': /* Cancel the rest of the output. */ case L'c': /* Cancel the rest of the output. */
this->early_exit = true; this->early_exit = true;
break; break;
case L'e': /* Escape */
this->append_output(L'\x1B');
break;
case L'f': /* Form feed. */ case L'f': /* Form feed. */
this->append_output(L'\f'); this->append_output(L'\f');
break; break;
@@ -361,22 +358,19 @@ long builtin_printf_state_t::print_esc(const wchar_t *escstart, bool octal_0)
esc_value = esc_value * 16 + hex_to_bin(*p); esc_value = esc_value * 16 + hex_to_bin(*p);
if (esc_length == 0) if (esc_length == 0)
this->fatal_error(_(L"missing hexadecimal number in escape")); this->fatal_error(_(L"missing hexadecimal number in escape"));
this->append_output(ENCODE_DIRECT_BASE + esc_value % 256); this->append_format_output(L"%lc", esc_value);
} }
else if (is_octal_digit(*p)) else if (is_octal_digit(*p))
{ {
/* Parse \0ooo (if octal_0 && *p == L'0') or \ooo (otherwise). /* Parse \0ooo (if octal_0 && *p == L'0') or \ooo (otherwise).
Allow \ooo if octal_0 && *p != L'0'; this is an undocumented Allow \ooo if octal_0 && *p != L'0'; this is an undocumented
extension to POSIX that is compatible with Bash 2.05b. */ extension to POSIX that is compatible with Bash 2.05b. */
/* Wrap mod 256, which matches historic behavior */
for (esc_length = 0, p += octal_0 && *p == L'0'; esc_length < 3 && is_octal_digit(*p); ++esc_length, ++p) for (esc_length = 0, p += octal_0 && *p == L'0'; esc_length < 3 && is_octal_digit(*p); ++esc_length, ++p)
esc_value = esc_value * 8 + octal_to_bin(*p); esc_value = esc_value * 8 + octal_to_bin(*p);
this->append_output(ENCODE_DIRECT_BASE + esc_value % 256); this->append_format_output(L"%c", esc_value);
} }
else if (*p && wcschr(L"\"\\abcefnrtv", *p)) else if (*p && wcschr(L"\"\\abcfnrtv", *p))
{
print_esc_char(*p++); print_esc_char(*p++);
}
else if (*p == L'u' || *p == L'U') else if (*p == L'u' || *p == L'U')
{ {
wchar_t esc_char = *p; wchar_t esc_char = *p;
@@ -472,7 +466,6 @@ void builtin_printf_state_t::print_direc(const wchar_t *start, size_t length, wc
fmt.append(L"L"); fmt.append(L"L");
break; break;
case L's': case L's':
case L'c':
fmt.append(L"l"); fmt.append(L"l");
break; break;
default: default:
@@ -582,16 +575,6 @@ void builtin_printf_state_t::print_direc(const wchar_t *start, size_t length, wc
} }
} }
/* For each character in str, set the corresponding boolean in the array to the given flag */
static inline void modify_allowed_format_specifiers(bool ok[UCHAR_MAX + 1], const char *str, bool flag)
{
for (const char *c = str; *c != '\0'; c++)
{
unsigned char idx = static_cast<unsigned char>(*c);
ok[idx] = flag;
}
}
/* Print the text in FORMAT, using ARGV (with ARGC elements) for /* Print the text in FORMAT, using ARGV (with ARGC elements) for
arguments to any `%' directives. arguments to any `%' directives.
Return the number of elements of ARGV used. */ Return the number of elements of ARGV used. */
@@ -634,7 +617,9 @@ int builtin_printf_state_t::print_formatted(const wchar_t *format, int argc, wch
break; break;
} }
modify_allowed_format_specifiers(ok, "aAcdeEfFgGiosuxX", true); ok['a'] = ok['A'] = ok['c'] = ok['d'] = ok['e'] = ok['E'] =
ok['f'] = ok['F'] = ok['g'] = ok['G'] = ok['i'] = ok['o'] =
ok['s'] = ok['u'] = ok['x'] = ok['X'] = true;
for (;; f++, direc_length++) for (;; f++, direc_length++)
{ {
@@ -642,17 +627,18 @@ int builtin_printf_state_t::print_formatted(const wchar_t *format, int argc, wch
{ {
case L'I': case L'I':
case L'\'': case L'\'':
modify_allowed_format_specifiers(ok, "aAceEosxX", false); ok['a'] = ok['A'] = ok['c'] = ok['e'] = ok['E'] =
ok['o'] = ok['s'] = ok['x'] = ok['X'] = false;
break; break;
case '-': case '-':
case '+': case '+':
case ' ': case ' ':
break; break;
case L'#': case L'#':
modify_allowed_format_specifiers(ok, "cdisu", false); ok['c'] = ok['d'] = ok['i'] = ok['s'] = ok['u'] = false;
break; break;
case '0': case '0':
modify_allowed_format_specifiers(ok, "cs", false); ok['c'] = ok['s'] = false;
break; break;
default: default:
goto no_more_flag_characters; goto no_more_flag_characters;
@@ -693,7 +679,7 @@ no_more_flag_characters:
{ {
++f; ++f;
++direc_length; ++direc_length;
modify_allowed_format_specifiers(ok, "c", false); ok['c'] = false;
if (*f == L'*') if (*f == L'*')
{ {
++f; ++f;
@@ -737,8 +723,8 @@ no_more_flag_characters:
++f; ++f;
{ {
wchar_t conversion = *f; unsigned wchar_t conversion = *f;
if (conversion > 0xFF || ! ok[conversion]) if (! ok[conversion])
{ {
this->fatal_error(_(L"%.*ls: invalid conversion specification"), (int)(f + 1 - direc_start), direc_start); this->fatal_error(_(L"%.*ls: invalid conversion specification"), (int)(f + 1 - direc_start), direc_start);
return 0; return 0;
@@ -762,9 +748,9 @@ no_more_flag_characters:
return save_argc - argc; return save_argc - argc;
} }
static int builtin_printf(parser_t &parser, io_streams_t &streams, wchar_t **argv) static int builtin_printf(parser_t &parser, wchar_t **argv)
{ {
builtin_printf_state_t state(streams); builtin_printf_state_t state;
wchar_t *format; wchar_t *format;
int args_used; int args_used;

View File

@@ -26,6 +26,9 @@ Functions used for implementing the set builtin.
#include "proc.h" #include "proc.h"
#include "parser.h" #include "parser.h"
/* We know about these buffers */
extern wcstring stdout_buffer, stderr_buffer;
/** /**
Error message for invalid path operations Error message for invalid path operations
*/ */
@@ -53,7 +56,7 @@ static int is_path_variable(const wchar_t *env)
Call env_set. If this is a path variable, e.g. PATH, validate the Call env_set. If this is a path variable, e.g. PATH, validate the
elements. On error, print a description of the problem to stderr. elements. On error, print a description of the problem to stderr.
*/ */
static int my_env_set(const wchar_t *key, const wcstring_list_t &val, int scope, io_streams_t &streams) static int my_env_set(const wchar_t *key, const wcstring_list_t &val, int scope)
{ {
size_t i; size_t i;
int retcode = 0; int retcode = 0;
@@ -64,22 +67,16 @@ static int my_env_set(const wchar_t *key, const wcstring_list_t &val, int scope,
/* Fix for https://github.com/fish-shell/fish-shell/issues/199 . Return success if any path setting succeeds. */ /* Fix for https://github.com/fish-shell/fish-shell/issues/199 . Return success if any path setting succeeds. */
bool any_success = false; bool any_success = false;
/* Don't bother validating (or complaining about) values that are already present. /* Don't bother validating (or complaining about) values that are already present */
When determining already-present values, use ENV_DEFAULT instead of the passed-in scope because in:
set -l PATH stuff $PATH
where we are temporarily shadowing a variable, we want to compare against the shadowed value, not the
(missing) local value.
Also don't bother to complain about relative paths, which don't start with /.
*/
wcstring_list_t existing_values; wcstring_list_t existing_values;
const env_var_t existing_variable = env_get_string(key, ENV_DEFAULT); const env_var_t existing_variable = env_get_string(key);
if (! existing_variable.missing_or_empty()) if (! existing_variable.missing_or_empty())
tokenize_variable_array(existing_variable, existing_values); tokenize_variable_array(existing_variable, existing_values);
for (i=0; i< val.size() ; i++) for (i=0; i< val.size() ; i++)
{ {
const wcstring &dir = val.at(i); const wcstring &dir = val.at(i);
if (!string_prefixes_string(L"/", dir) || list_contains_string(existing_values, dir)) if (list_contains_string(existing_values, dir))
{ {
any_success = true; any_success = true;
continue; continue;
@@ -107,7 +104,7 @@ static int my_env_set(const wchar_t *key, const wcstring_list_t &val, int scope,
} }
else else
{ {
streams.err.append_format(_(BUILTIN_SET_PATH_ERROR), L"set", dir.c_str(), key); append_format(stderr_buffer, _(BUILTIN_SET_PATH_ERROR), L"set", dir.c_str(), key);
const wchar_t *colon = wcschr(dir.c_str(), L':'); const wchar_t *colon = wcschr(dir.c_str(), L':');
if (colon && *(colon+1)) if (colon && *(colon+1))
@@ -119,12 +116,12 @@ static int my_env_set(const wchar_t *key, const wcstring_list_t &val, int scope,
if (show_perror) if (show_perror)
{ {
builtin_wperror(L"set", streams); builtin_wperror(L"set");
} }
if (show_hint) if (show_hint)
{ {
streams.err.append_format(_(BUILTIN_SET_PATH_HINT), L"set", key, key, wcschr(dir.c_str(), L':')+1); append_format(stderr_buffer, _(BUILTIN_SET_PATH_HINT), L"set", key, key, wcschr(dir.c_str(), L':')+1);
} }
} }
@@ -155,21 +152,14 @@ static int my_env_set(const wchar_t *key, const wcstring_list_t &val, int scope,
{ {
case ENV_PERM: case ENV_PERM:
{ {
streams.err.append_format(_(L"%ls: Tried to change the read-only variable '%ls'\n"), L"set", key); append_format(stderr_buffer, _(L"%ls: Tried to change the read-only variable '%ls'\n"), L"set", key);
retcode=1;
break;
}
case ENV_SCOPE:
{
streams.err.append_format(_(L"%ls: Tried to set the special variable '%ls' with the wrong scope\n"), L"set", key);
retcode=1; retcode=1;
break; break;
} }
case ENV_INVALID: case ENV_INVALID:
{ {
streams.err.append_format(_(L"%ls: Tried to set the special variable '%ls' to an invalid value\n"), L"set", key); append_format(stderr_buffer, _(L"%ls: Unknown error"), L"set");
retcode=1; retcode=1;
break; break;
} }
@@ -193,8 +183,7 @@ static int my_env_set(const wchar_t *key, const wcstring_list_t &val, int scope,
static int parse_index(std::vector<long> &indexes, static int parse_index(std::vector<long> &indexes,
const wchar_t *src, const wchar_t *src,
const wchar_t *name, const wchar_t *name,
size_t var_count, size_t var_count)
io_streams_t &streams)
{ {
size_t len; size_t len;
@@ -213,7 +202,7 @@ static int parse_index(std::vector<long> &indexes,
if (*src != L'[') if (*src != L'[')
{ {
streams.err.append_format(_(BUILTIN_SET_ARG_COUNT), L"set"); append_format(stderr_buffer, _(BUILTIN_SET_ARG_COUNT), L"set");
return 0; return 0;
} }
@@ -221,7 +210,8 @@ static int parse_index(std::vector<long> &indexes,
if ((wcsncmp(src_orig, name, len)!=0) || (wcslen(name) != (len))) if ((wcsncmp(src_orig, name, len)!=0) || (wcslen(name) != (len)))
{ {
streams.err.append_format(_(L"%ls: Multiple variable names specified in single call (%ls and %.*ls)\n"), append_format(stderr_buffer,
_(L"%ls: Multiple variable names specified in single call (%ls and %.*ls)\n"),
L"set", L"set",
name, name,
len, len,
@@ -248,7 +238,7 @@ static int parse_index(std::vector<long> &indexes,
if (end==src || errno) if (end==src || errno)
{ {
streams.err.append_format(_(L"%ls: Invalid index starting at '%ls'\n"), L"set", src); append_format(stderr_buffer, _(L"%ls: Invalid index starting at '%ls'\n"), L"set", src);
return 0; return 0;
} }
@@ -349,7 +339,7 @@ static void erase_values(wcstring_list_t &list, const std::vector<long> &indexes
Print the names of all environment variables in the scope, with or without shortening, Print the names of all environment variables in the scope, with or without shortening,
with or without values, with or without escaping with or without values, with or without escaping
*/ */
static void print_variables(int include_values, int esc, bool shorten_ok, int scope, io_streams_t &streams) static void print_variables(int include_values, int esc, bool shorten_ok, int scope)
{ {
wcstring_list_t names = env_get_names(scope); wcstring_list_t names = env_get_names(scope);
sort(names.begin(), names.end()); sort(names.begin(), names.end());
@@ -359,11 +349,11 @@ static void print_variables(int include_values, int esc, bool shorten_ok, int sc
const wcstring key = names.at(i); const wcstring key = names.at(i);
const wcstring e_key = escape_string(key, 0); const wcstring e_key = escape_string(key, 0);
streams.out.append(e_key); stdout_buffer.append(e_key);
if (include_values) if (include_values)
{ {
env_var_t value = env_get_string(key, scope); env_var_t value = env_get_string(key);
if (!value.missing()) if (!value.missing())
{ {
int shorten = 0; int shorten = 0;
@@ -376,18 +366,18 @@ static void print_variables(int include_values, int esc, bool shorten_ok, int sc
wcstring e_value = esc ? expand_escape_variable(value) : value; wcstring e_value = esc ? expand_escape_variable(value) : value;
streams.out.append(L" "); stdout_buffer.append(L" ");
streams.out.append(e_value); stdout_buffer.append(e_value);
if (shorten) if (shorten)
{ {
streams.out.push_back(ellipsis_char); stdout_buffer.push_back(ellipsis_char);
} }
} }
} }
streams.out.append(L"\n"); stdout_buffer.append(L"\n");
} }
} }
@@ -397,9 +387,8 @@ static void print_variables(int include_values, int esc, bool shorten_ok, int sc
The set builtin. Creates, updates and erases environment variables The set builtin. Creates, updates and erases environment variables
and environemnt variable arrays. and environemnt variable arrays.
*/ */
static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv) static int builtin_set(parser_t &parser, wchar_t **argv)
{ {
wgetopter_t w;
/** Variables used for parsing the argument list */ /** Variables used for parsing the argument list */
const struct woption long_options[] = const struct woption long_options[] =
{ {
@@ -437,15 +426,16 @@ static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv)
int retcode=0; int retcode=0;
int scope; int scope;
int slice=0; int slice=0;
int i;
const wchar_t *bad_char = NULL; wchar_t *bad_char;
/* Parse options to obtain the requested operation and the modifiers */ /* Parse options to obtain the requested operation and the modifiers */
w.woptind = 0; woptind = 0;
while (1) while (1)
{ {
int c = w.wgetopt_long(argc, argv, short_options, long_options, 0); int c = wgetopt_long(argc, argv, short_options, long_options, 0);
if (c == -1) if (c == -1)
{ {
@@ -497,11 +487,11 @@ static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv)
break; break;
case 'h': case 'h':
builtin_print_help(parser, streams, argv[0], streams.out); builtin_print_help(parser, argv[0], stdout_buffer);
return 0; return 0;
case '?': case '?':
builtin_unknown_option(parser, streams, argv[0], argv[w.woptind-1]); builtin_unknown_option(parser, argv[0], argv[woptind-1]);
return 1; return 1;
default: default:
@@ -520,21 +510,23 @@ static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv)
if (query && (erase || list)) if (query && (erase || list))
{ {
streams.err.append_format(BUILTIN_ERR_COMBO, append_format(stderr_buffer,
BUILTIN_ERR_COMBO,
argv[0]); argv[0]);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
/* We can't both list and erase variables */ /* We can't both list and erase varaibles */
if (erase && list) if (erase && list)
{ {
streams.err.append_format(BUILTIN_ERR_COMBO, append_format(stderr_buffer,
BUILTIN_ERR_COMBO,
argv[0]); argv[0]);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
@@ -543,9 +535,10 @@ static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv)
*/ */
if (local + global + universal > 1) if (local + global + universal > 1)
{ {
streams.err.append_format(BUILTIN_ERR_GLOCAL, append_format(stderr_buffer,
BUILTIN_ERR_GLOCAL,
argv[0]); argv[0]);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
@@ -554,9 +547,10 @@ static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv)
*/ */
if (exportv && unexport) if (exportv && unexport)
{ {
streams.err.append_format(BUILTIN_ERR_EXPUNEXP, append_format(stderr_buffer,
BUILTIN_ERR_EXPUNEXP,
argv[0]); argv[0]);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
@@ -572,7 +566,7 @@ static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv)
out of the specified variables. out of the specified variables.
*/ */
int i; int i;
for (i=w.woptind; i<argc; i++) for (i=woptind; i<argc; i++)
{ {
wchar_t *arg = argv[i]; wchar_t *arg = argv[i];
int slice=0; int slice=0;
@@ -594,13 +588,13 @@ static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv)
wcstring_list_t result; wcstring_list_t result;
size_t j; size_t j;
env_var_t dest_str = env_get_string(dest, scope); env_var_t dest_str = env_get_string(dest);
if (! dest_str.missing()) if (! dest_str.missing())
tokenize_variable_array(dest_str, result); tokenize_variable_array(dest_str, result);
if (!parse_index(indexes, arg, dest, result.size(), streams)) if (!parse_index(indexes, arg, dest, result.size()))
{ {
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
retcode = 1; retcode = 1;
break; break;
} }
@@ -630,11 +624,11 @@ static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv)
if (list) if (list)
{ {
/* Maybe we should issue an error if there are any other arguments? */ /* Maybe we should issue an error if there are any other arguments? */
print_variables(0, 0, shorten_ok, scope, streams); print_variables(0, 0, shorten_ok, scope);
return 0; return 0;
} }
if (w.woptind == argc) if (woptind == argc)
{ {
/* /*
Print values of variables Print values of variables
@@ -642,21 +636,22 @@ static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv)
if (erase) if (erase)
{ {
streams.err.append_format(_(L"%ls: Erase needs a variable name\n"), append_format(stderr_buffer,
_(L"%ls: Erase needs a variable name\n"),
argv[0]); argv[0]);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
retcode = 1; retcode = 1;
} }
else else
{ {
print_variables(1, 1, shorten_ok, scope, streams); print_variables(1, 1, shorten_ok, scope);
} }
return retcode; return retcode;
} }
if (!(dest = wcsdup(argv[w.woptind]))) if (!(dest = wcsdup(argv[woptind])))
{ {
DIE_MEM(); DIE_MEM();
} }
@@ -670,19 +665,27 @@ static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv)
if (!wcslen(dest)) if (!wcslen(dest))
{ {
free(dest); free(dest);
streams.err.append_format(BUILTIN_ERR_VARNAME_ZERO, argv[0]); append_format(stderr_buffer, BUILTIN_ERR_VARNAME_ZERO, argv[0]);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
if ((bad_char = wcsvarname(dest))) if ((bad_char = wcsvarname(dest)))
{ {
streams.err.append_format(BUILTIN_ERR_VARCHAR, argv[0], *bad_char); append_format(stderr_buffer, BUILTIN_ERR_VARCHAR, argv[0], *bad_char);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
free(dest); free(dest);
return 1; return 1;
} }
if (slice && erase && (scope != ENV_USER))
{
free(dest);
append_format(stderr_buffer, _(L"%ls: Can not specify scope when erasing array slice\n"), argv[0]);
builtin_print_help(parser, argv[0], stderr_buffer);
return 1;
}
/* /*
set assignment can work in two modes, either using slices or set assignment can work in two modes, either using slices or
using the whole array. We detect which mode is used here. using the whole array. We detect which mode is used here.
@@ -694,47 +697,40 @@ static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv)
/* /*
Slice mode Slice mode
*/ */
size_t idx_count, val_count;
wcstring_list_t values;
std::vector<long> indexes; std::vector<long> indexes;
wcstring_list_t result; wcstring_list_t result;
const env_var_t dest_str = env_get_string(dest, scope); const env_var_t dest_str = env_get_string(dest);
if (! dest_str.missing()) if (! dest_str.missing())
{
tokenize_variable_array(dest_str, result); tokenize_variable_array(dest_str, result);
}
else if (erase)
{
retcode = 1;
}
if (!retcode) for (; woptind<argc; woptind++)
{ {
for (; w.woptind<argc; w.woptind++) if (!parse_index(indexes, argv[woptind], dest, result.size()))
{ {
if (!parse_index(indexes, argv[w.woptind], dest, result.size(), streams)) builtin_print_help(parser, argv[0], stderr_buffer);
retcode = 1;
break;
}
val_count = argc-woptind-1;
idx_count = indexes.size();
if (!erase)
{
if (val_count < idx_count)
{ {
builtin_print_help(parser, streams, argv[0], streams.err); append_format(stderr_buffer, _(BUILTIN_SET_ARG_COUNT), argv[0]);
retcode = 1; builtin_print_help(parser, argv[0], stderr_buffer);
retcode=1;
break; break;
} }
if (val_count == idx_count)
size_t idx_count = indexes.size();
size_t val_count = argc-w.woptind-1;
if (!erase)
{ {
if (val_count < idx_count) woptind++;
{ break;
streams.err.append_format(_(BUILTIN_SET_ARG_COUNT), argv[0]);
builtin_print_help(parser, streams, argv[0], streams.err);
retcode=1;
break;
}
if (val_count == idx_count)
{
w.woptind++;
break;
}
} }
} }
} }
@@ -748,27 +744,27 @@ static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv)
if (erase) if (erase)
{ {
erase_values(result, indexes); erase_values(result, indexes);
my_env_set(dest, result, scope, streams); my_env_set(dest, result, scope);
} }
else else
{ {
wcstring_list_t value; wcstring_list_t value;
while (w.woptind < argc) while (woptind < argc)
{ {
value.push_back(argv[w.woptind++]); value.push_back(argv[woptind++]);
} }
if (update_values(result, if (update_values(result,
indexes, indexes,
value)) value))
{ {
streams.err.append_format(L"%ls: ", argv[0]); append_format(stderr_buffer, L"%ls: ", argv[0]);
streams.err.append_format(ARRAY_BOUNDS_ERR); append_format(stderr_buffer, ARRAY_BOUNDS_ERR);
streams.err.push_back(L'\n'); stderr_buffer.push_back(L'\n');
} }
my_env_set(dest, result, scope, streams); my_env_set(dest, result, scope);
} }
@@ -776,18 +772,19 @@ static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv)
} }
else else
{ {
w.woptind++; woptind++;
/* /*
No slicing No slicing
*/ */
if (erase) if (erase)
{ {
if (w.woptind != argc) if (woptind != argc)
{ {
streams.err.append_format(_(L"%ls: Values cannot be specfied with erase\n"), append_format(stderr_buffer,
_(L"%ls: Values cannot be specfied with erase\n"),
argv[0]); argv[0]);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
retcode=1; retcode=1;
} }
else else
@@ -798,22 +795,12 @@ static int builtin_set(parser_t &parser, io_streams_t &streams, wchar_t **argv)
else else
{ {
wcstring_list_t val; wcstring_list_t val;
for (int i=w.woptind; i<argc; i++) for (i=woptind; i<argc; i++)
val.push_back(argv[i]); val.push_back(argv[i]);
retcode = my_env_set(dest, val, scope, streams); retcode = my_env_set(dest, val, scope);
} }
} }
/* Check if we are setting variables above the effective scope.
See https://github.com/fish-shell/fish-shell/issues/806
*/
env_var_t global_dest = env_get_string(dest, ENV_GLOBAL);
if (universal && ! global_dest.missing())
{
streams.err.append_format(_(L"%ls: Warning: universal scope selected, but a global variable '%ls' exists.\n"), L"set", dest);
}
free(dest); free(dest);
if (retcode == STATUS_BUILTIN_OK && preserve_incoming_failure_exit_status) if (retcode == STATUS_BUILTIN_OK && preserve_incoming_failure_exit_status)

View File

@@ -11,8 +11,6 @@ Functions used for implementing the set_color builtin.
#if HAVE_NCURSES_H #if HAVE_NCURSES_H
#include <ncurses.h> #include <ncurses.h>
#elif HAVE_NCURSES_CURSES_H
#include <ncurses/curses.h>
#else #else
#include <curses.h> #include <curses.h>
#endif #endif
@@ -24,6 +22,9 @@ Functions used for implementing the set_color builtin.
#endif #endif
/* We know about these buffers */
extern wcstring stdout_buffer, stderr_buffer;
/** /**
Error message for invalid path operations Error message for invalid path operations
*/ */
@@ -39,14 +40,14 @@ Functions used for implementing the set_color builtin.
*/ */
#define BUILTIN_SET_ARG_COUNT L"%ls: The number of variable indexes does not match the number of values\n" #define BUILTIN_SET_ARG_COUNT L"%ls: The number of variable indexes does not match the number of values\n"
static void print_colors(io_streams_t &streams) static void print_colors(void)
{ {
const wcstring_list_t result = rgb_color_t::named_color_names(); const wcstring_list_t result = rgb_color_t::named_color_names();
size_t i; size_t i;
for (i=0; i < result.size(); i++) for (i=0; i < result.size(); i++)
{ {
streams.out.append(result.at(i)); stdout_buffer.append(result.at(i));
streams.out.push_back(L'\n'); stdout_buffer.push_back(L'\n');
} }
} }
@@ -62,9 +63,8 @@ static int set_color_builtin_outputter(char c)
/** /**
set_color builtin set_color builtin
*/ */
static int builtin_set_color(parser_t &parser, io_streams_t &streams, wchar_t **argv) static int builtin_set_color(parser_t &parser, wchar_t **argv)
{ {
wgetopter_t w;
/** Variables used for parsing the argument list */ /** Variables used for parsing the argument list */
const struct woption long_options[] = const struct woption long_options[] =
{ {
@@ -81,21 +81,15 @@ static int builtin_set_color(parser_t &parser, io_streams_t &streams, wchar_t **
int argc = builtin_count_args(argv); int argc = builtin_count_args(argv);
/* Some code passes variables to set_color that don't exist, like $fish_user_whatever. As a hack, quietly return failure. */
if (argc <= 1)
{
return EXIT_FAILURE;
}
const wchar_t *bgcolor = NULL; const wchar_t *bgcolor = NULL;
bool bold = false, underline=false; bool bold = false, underline=false;
int errret; int errret;
/* Parse options to obtain the requested operation and the modifiers */ /* Parse options to obtain the requested operation and the modifiers */
w.woptind = 0; woptind = 0;
while (1) while (1)
{ {
int c = w.wgetopt_long(argc, argv, short_options, long_options, 0); int c = wgetopt_long(argc, argv, short_options, long_options, 0);
if (c == -1) if (c == -1)
{ {
@@ -108,11 +102,11 @@ static int builtin_set_color(parser_t &parser, io_streams_t &streams, wchar_t **
break; break;
case 'b': case 'b':
bgcolor = w.woptarg; bgcolor = woptarg;
break; break;
case 'h': case 'h':
builtin_print_help(parser, streams, argv[0], streams.out); builtin_print_help(parser, argv[0], stdout_buffer);
return STATUS_BUILTIN_OK; return STATUS_BUILTIN_OK;
case 'o': case 'o':
@@ -124,7 +118,7 @@ static int builtin_set_color(parser_t &parser, io_streams_t &streams, wchar_t **
break; break;
case 'c': case 'c':
print_colors(streams); print_colors();
return STATUS_BUILTIN_OK; return STATUS_BUILTIN_OK;
case '?': case '?':
@@ -132,42 +126,49 @@ static int builtin_set_color(parser_t &parser, io_streams_t &streams, wchar_t **
} }
} }
/* Remaining arguments are foreground color */ /* Remaining argument is foreground color */
std::vector<rgb_color_t> fgcolors; const wchar_t *fgcolor = NULL;
for (; w.woptind < argc; w.woptind++) if (woptind < argc)
{ {
rgb_color_t fg = rgb_color_t(argv[w.woptind]); if (woptind + 1 == argc)
if (fg.is_none())
{ {
streams.err.append_format(_(L"%ls: Unknown color '%ls'\n"), argv[0], argv[w.woptind]); fgcolor = argv[woptind];
}
else
{
append_format(stderr_buffer,
_(L"%ls: Too many arguments\n"),
argv[0]);
return STATUS_BUILTIN_ERROR; return STATUS_BUILTIN_ERROR;
} }
fgcolors.push_back(fg);
} }
if (fgcolors.empty() && bgcolor == NULL && !bold && !underline) if (fgcolor == NULL && bgcolor == NULL && !bold && !underline)
{ {
streams.err.append_format(_(L"%ls: Expected an argument\n"), append_format(stderr_buffer,
_(L"%ls: Expected an argument\n"),
argv[0]); argv[0]);
return STATUS_BUILTIN_ERROR; return STATUS_BUILTIN_ERROR;
} }
// #1323: We may have multiple foreground colors. Choose the best one. const rgb_color_t fg = rgb_color_t(fgcolor ? fgcolor : L"");
// If we had no foreground coor, we'll get none(); if we have at least one we expect not-none if (fgcolor && fg.is_none())
const rgb_color_t fg = best_color(fgcolors, output_get_color_support()); {
assert(fgcolors.empty() || !fg.is_none()); append_format(stderr_buffer, _(L"%ls: Unknown color '%ls'\n"), argv[0], fgcolor);
return STATUS_BUILTIN_ERROR;
}
const rgb_color_t bg = rgb_color_t(bgcolor ? bgcolor : L""); const rgb_color_t bg = rgb_color_t(bgcolor ? bgcolor : L"");
if (bgcolor && bg.is_none()) if (bgcolor && bg.is_none())
{ {
streams.err.append_format(_(L"%ls: Unknown color '%ls'\n"), argv[0], bgcolor); append_format(stderr_buffer, _(L"%ls: Unknown color '%ls'\n"), argv[0], bgcolor);
return STATUS_BUILTIN_ERROR; return STATUS_BUILTIN_ERROR;
} }
/* Make sure that the term exists */ /* Make sure that the term exists */
if (cur_term == NULL && setupterm(0, STDOUT_FILENO, &errret) == ERR) if (cur_term == NULL && setupterm(0, STDOUT_FILENO, &errret) == ERR)
{ {
streams.err.append_format(_(L"%ls: Could not set up terminal\n"), argv[0]); append_format(stderr_buffer, _(L"%ls: Could not set up terminal\n"), argv[0]);
return STATUS_BUILTIN_ERROR; return STATUS_BUILTIN_ERROR;
} }
@@ -180,6 +181,7 @@ static int builtin_set_color(parser_t &parser, io_streams_t &streams, wchar_t **
return STATUS_BUILTIN_ERROR; return STATUS_BUILTIN_ERROR;
} }
/* Save old output function so we can restore it */ /* Save old output function so we can restore it */
int (* const saved_writer_func)(char) = output_get_writer(); int (* const saved_writer_func)(char) = output_get_writer();
@@ -203,29 +205,29 @@ static int builtin_set_color(parser_t &parser, io_streams_t &streams, wchar_t **
{ {
if (bg.is_normal()) if (bg.is_normal())
{ {
write_color(rgb_color_t::black(), false /* not is_fg */); write_background_color(0);
writembs(tparm(exit_attribute_mode)); writembs(tparm(exit_attribute_mode));
} }
} }
if (! fg.is_none()) if (fgcolor != NULL)
{ {
if (fg.is_normal() || fg.is_reset()) if (fg.is_normal())
{ {
write_color(rgb_color_t::black(), true /* is_fg */); write_foreground_color(0);
writembs(tparm(exit_attribute_mode)); writembs(tparm(exit_attribute_mode));
} }
else else
{ {
write_color(fg, true /* is_fg */); write_foreground_color(index_for_color(fg));
} }
} }
if (bgcolor != NULL) if (bgcolor != NULL)
{ {
if (! bg.is_normal() && ! bg.is_reset()) if (! bg.is_normal())
{ {
write_color(bg, false /* not is_fg */); write_background_color(index_for_color(bg));
} }
} }
@@ -233,8 +235,9 @@ static int builtin_set_color(parser_t &parser, io_streams_t &streams, wchar_t **
output_set_writer(saved_writer_func); output_set_writer(saved_writer_func);
/* Output the collected string */ /* Output the collected string */
streams.out.append(str2wcstring(builtin_set_color_output)); std::string local_output;
builtin_set_color_output.clear(); std::swap(builtin_set_color_output, local_output);
stdout_buffer.append(str2wcstring(local_output));
return STATUS_BUILTIN_OK; return STATUS_BUILTIN_OK;
} }

View File

@@ -10,8 +10,6 @@ Implemented from scratch (yes, really) by way of IEEE 1003.1 as reference.
#include "builtin.h" #include "builtin.h"
#include "wutil.h" #include "wutil.h"
#include "proc.h" #include "proc.h"
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <memory> #include <memory>
@@ -23,7 +21,13 @@ enum
}; };
int builtin_test(parser_t &parser, io_streams_t &streams, wchar_t **argv); int builtin_test(parser_t &parser, wchar_t **argv);
static const wchar_t * const condstr[] =
{
L"!", L"&&", L"||", L"==", L"!=", L"<", L">", L"-nt", L"-ot", L"-ef", L"-eq",
L"-ne", L"-lt", L"-gt", L"-le", L"-ge", L"=~"
};
namespace test_expressions namespace test_expressions
{ {
@@ -35,15 +39,13 @@ enum token_t
test_bang, // "!", inverts sense test_bang, // "!", inverts sense
test_filetype_b, // "-b", for block special files test_filetype_b, // "-b", for block special files
test_filetype_c, // "-c", for character special files test_filetype_c, // "-c" for character special files
test_filetype_d, // "-d", for directories test_filetype_d, // "-d" for directories
test_filetype_e, // "-e", for files that exist test_filetype_e, // "-e" for files that exist
test_filetype_f, // "-f", for for regular files test_filetype_f, // "-f" for for regular files
test_filetype_G, // "-G", for check effective group id test_filetype_g, // "-g" for set-group-id
test_filetype_g, // "-g", for set-group-id test_filetype_h, // "-h" for symbolic links
test_filetype_h, // "-h", for symbolic links
test_filetype_L, // "-L", same as -h test_filetype_L, // "-L", same as -h
test_filetype_O, // "-O", for check effective user id
test_filetype_p, // "-p", for FIFO test_filetype_p, // "-p", for FIFO
test_filetype_S, // "-S", socket test_filetype_S, // "-S", socket
@@ -99,11 +101,9 @@ static const struct token_info_t
{test_filetype_d, L"-d", UNARY_PRIMARY}, {test_filetype_d, L"-d", UNARY_PRIMARY},
{test_filetype_e, L"-e", UNARY_PRIMARY}, {test_filetype_e, L"-e", UNARY_PRIMARY},
{test_filetype_f, L"-f", UNARY_PRIMARY}, {test_filetype_f, L"-f", UNARY_PRIMARY},
{test_filetype_G, L"-G", UNARY_PRIMARY},
{test_filetype_g, L"-g", UNARY_PRIMARY}, {test_filetype_g, L"-g", UNARY_PRIMARY},
{test_filetype_h, L"-h", UNARY_PRIMARY}, {test_filetype_h, L"-h", UNARY_PRIMARY},
{test_filetype_L, L"-L", UNARY_PRIMARY}, {test_filetype_L, L"-L", UNARY_PRIMARY},
{test_filetype_O, L"-O", UNARY_PRIMARY},
{test_filetype_p, L"-p", UNARY_PRIMARY}, {test_filetype_p, L"-p", UNARY_PRIMARY},
{test_filetype_S, L"-S", UNARY_PRIMARY}, {test_filetype_S, L"-S", UNARY_PRIMARY},
{test_filesize_s, L"-s", UNARY_PRIMARY}, {test_filesize_s, L"-s", UNARY_PRIMARY},
@@ -173,7 +173,7 @@ private:
} }
public: public:
explicit test_parser(const wcstring_list_t &val) : strings(val) test_parser(const wcstring_list_t &val) : strings(val)
{ } { }
expression *parse_expression(unsigned int start, unsigned int end); expression *parse_expression(unsigned int start, unsigned int end);
@@ -648,11 +648,13 @@ expression *test_parser::parse_args(const wcstring_list_t &args, wcstring &err)
expression *result = parser.parse_expression(0, (unsigned int)args.size()); expression *result = parser.parse_expression(0, (unsigned int)args.size());
/* Handle errors */ /* Handle errors */
bool errored = false;
for (size_t i = 0; i < parser.errors.size(); i++) for (size_t i = 0; i < parser.errors.size(); i++)
{ {
err.append(L"test: "); err.append(L"test: ");
err.append(parser.errors.at(i)); err.append(parser.errors.at(i));
err.push_back(L'\n'); err.push_back(L'\n');
errored = true;
// For now we only show the first error // For now we only show the first error
break; break;
} }
@@ -667,12 +669,14 @@ expression *test_parser::parse_args(const wcstring_list_t &args, wcstring &err)
{ {
append_format(err, L"test: unexpected argument at index %lu: '%ls'\n", (unsigned long)result->range.end, args.at(result->range.end).c_str()); append_format(err, L"test: unexpected argument at index %lu: '%ls'\n", (unsigned long)result->range.end, args.at(result->range.end).c_str());
} }
errored = true;
delete result; delete result;
result = NULL; result = NULL;
} }
} }
return result; return result;
} }
@@ -814,31 +818,25 @@ static bool unary_primary_evaluate(test_expressions::token_t token, const wcstri
case test_filetype_b: // "-b", for block special files case test_filetype_b: // "-b", for block special files
return !wstat(arg, &buf) && S_ISBLK(buf.st_mode); return !wstat(arg, &buf) && S_ISBLK(buf.st_mode);
case test_filetype_c: // "-c", for character special files case test_filetype_c: // "-c" for character special files
return !wstat(arg, &buf) && S_ISCHR(buf.st_mode); return !wstat(arg, &buf) && S_ISCHR(buf.st_mode);
case test_filetype_d: // "-d", for directories case test_filetype_d: // "-d" for directories
return !wstat(arg, &buf) && S_ISDIR(buf.st_mode); return !wstat(arg, &buf) && S_ISDIR(buf.st_mode);
case test_filetype_e: // "-e", for files that exist case test_filetype_e: // "-e" for files that exist
return !wstat(arg, &buf); return !wstat(arg, &buf);
case test_filetype_f: // "-f", for for regular files case test_filetype_f: // "-f" for for regular files
return !wstat(arg, &buf) && S_ISREG(buf.st_mode); return !wstat(arg, &buf) && S_ISREG(buf.st_mode);
case test_filetype_G: // "-G", for check effective group id case test_filetype_g: // "-g" for set-group-id
return !wstat(arg, &buf) && getegid() == buf.st_gid;
case test_filetype_g: // "-g", for set-group-id
return !wstat(arg, &buf) && (S_ISGID & buf.st_mode); return !wstat(arg, &buf) && (S_ISGID & buf.st_mode);
case test_filetype_h: // "-h", for symbolic links case test_filetype_h: // "-h" for symbolic links
case test_filetype_L: // "-L", same as -h case test_filetype_L: // "-L", same as -h
return !lwstat(arg, &buf) && S_ISLNK(buf.st_mode); return !lwstat(arg, &buf) && S_ISLNK(buf.st_mode);
case test_filetype_O: // "-O", for check effective user id
return !wstat(arg, &buf) && geteuid() == buf.st_uid;
case test_filetype_p: // "-p", for FIFO case test_filetype_p: // "-p", for FIFO
return !wstat(arg, &buf) && S_ISFIFO(buf.st_mode); return !wstat(arg, &buf) && S_ISFIFO(buf.st_mode);
@@ -887,7 +885,7 @@ static bool unary_primary_evaluate(test_expressions::token_t token, const wcstri
* Return status is the final shell status, i.e. 0 for true, * Return status is the final shell status, i.e. 0 for true,
* 1 for false and 2 for error. * 1 for false and 2 for error.
*/ */
int builtin_test(parser_t &parser, io_streams_t &streams, wchar_t **argv) int builtin_test(parser_t &parser, wchar_t **argv)
{ {
using namespace test_expressions; using namespace test_expressions;
@@ -912,7 +910,7 @@ int builtin_test(parser_t &parser, io_streams_t &streams, wchar_t **argv)
} }
else else
{ {
streams.err.append(L"[: the last argument must be ']'\n"); builtin_show_error(L"[: the last argument must be ']'\n");
return BUILTIN_TEST_FAIL; return BUILTIN_TEST_FAIL;
} }
@@ -948,7 +946,7 @@ int builtin_test(parser_t &parser, io_streams_t &streams, wchar_t **argv)
} }
printf("and returned parse error: %ls\n", err.c_str()); printf("and returned parse error: %ls\n", err.c_str());
#endif #endif
streams.err.append(err); builtin_show_error(err);
return BUILTIN_TEST_FAIL; return BUILTIN_TEST_FAIL;
} }
else else

View File

@@ -139,28 +139,28 @@ static rlim_t get(int resource, int hard)
/** /**
Print the value of the specified resource limit Print the value of the specified resource limit
*/ */
static void print(int resource, int hard, io_streams_t &streams) static void print(int resource, int hard)
{ {
rlim_t l = get(resource, hard); rlim_t l = get(resource, hard);
if (l == RLIM_INFINITY) if (l == RLIM_INFINITY)
streams.out.append(L"unlimited\n"); stdout_buffer.append(L"unlimited\n");
else else
streams.out.append_format( L"%d\n", l / get_multiplier(resource)); append_format(stdout_buffer, L"%d\n", l / get_multiplier(resource));
} }
/** /**
Print values of all resource limits Print values of all resource limits
*/ */
static void print_all(int hard, io_streams_t &streams) static void print_all(int hard)
{ {
int i; int i;
int w=0; int w=0;
for (i=0; resource_arr[i].desc; i++) for (i=0; resource_arr[i].desc; i++)
{ {
w=maxi(w, fish_wcswidth(resource_arr[i].desc)); w=maxi(w, my_wcswidth(resource_arr[i].desc));
} }
for (i=0; resource_arr[i].desc; i++) for (i=0; resource_arr[i].desc; i++)
@@ -172,7 +172,7 @@ static void print_all(int hard, io_streams_t &streams)
const wchar_t *unit = ((resource_arr[i].resource==RLIMIT_CPU)?L"(seconds, ":(get_multiplier(resource_arr[i].resource)==1?L"(":L"(kB, ")); const wchar_t *unit = ((resource_arr[i].resource==RLIMIT_CPU)?L"(seconds, ":(get_multiplier(resource_arr[i].resource)==1?L"(":L"(kB, "));
streams.out.append_format( append_format(stdout_buffer,
L"%-*ls %10ls-%lc) ", L"%-*ls %10ls-%lc) ",
w, w,
resource_arr[i].desc, resource_arr[i].desc,
@@ -181,11 +181,11 @@ static void print_all(int hard, io_streams_t &streams)
if (l == RLIM_INFINITY) if (l == RLIM_INFINITY)
{ {
streams.out.append(L"unlimited\n"); stdout_buffer.append(L"unlimited\n");
} }
else else
{ {
streams.out.append_format( L"%d\n", l/get_multiplier(resource_arr[i].resource)); append_format(stdout_buffer, L"%d\n", l/get_multiplier(resource_arr[i].resource));
} }
} }
@@ -213,7 +213,7 @@ static const wchar_t *get_desc(int what)
does _not_ multiply the limit value by the multiplier constant used does _not_ multiply the limit value by the multiplier constant used
by the commandline ulimit. by the commandline ulimit.
*/ */
static int set(int resource, int hard, int soft, rlim_t value, io_streams_t &streams) static int set(int resource, int hard, int soft, rlim_t value)
{ {
struct rlimit ls; struct rlimit ls;
getrlimit(resource, &ls); getrlimit(resource, &ls);
@@ -240,9 +240,9 @@ static int set(int resource, int hard, int soft, rlim_t value, io_streams_t &str
if (setrlimit(resource, &ls)) if (setrlimit(resource, &ls))
{ {
if (errno == EPERM) if (errno == EPERM)
streams.err.append_format(L"ulimit: Permission denied when changing resource of type '%ls'\n", get_desc(resource)); append_format(stderr_buffer, L"ulimit: Permission denied when changing resource of type '%ls'\n", get_desc(resource));
else else
builtin_wperror(L"ulimit", streams); builtin_wperror(L"ulimit");
return 1; return 1;
} }
return 0; return 0;
@@ -252,9 +252,8 @@ static int set(int resource, int hard, int soft, rlim_t value, io_streams_t &str
The ulimit builtin, used for setting resource limits. Defined in The ulimit builtin, used for setting resource limits. Defined in
builtin_ulimit.c. builtin_ulimit.c.
*/ */
static int builtin_ulimit(parser_t &parser, io_streams_t &streams, wchar_t **argv) static int builtin_ulimit(parser_t &parser, wchar_t ** argv)
{ {
wgetopter_t w;
int hard=0; int hard=0;
int soft=0; int soft=0;
@@ -263,7 +262,7 @@ static int builtin_ulimit(parser_t &parser, io_streams_t &streams, wchar_t **arg
int argc = builtin_count_args(argv); int argc = builtin_count_args(argv);
w.woptind=0; woptind=0;
while (1) while (1)
{ {
@@ -335,11 +334,11 @@ static int builtin_ulimit(parser_t &parser, io_streams_t &streams, wchar_t **arg
int opt_index = 0; int opt_index = 0;
int opt = w.wgetopt_long(argc, int opt = wgetopt_long(argc,
argv, argv,
L"aHScdflmnstuvh", L"aHScdflmnstuvh",
long_options, long_options,
&opt_index); &opt_index);
if (opt == -1) if (opt == -1)
break; break;
@@ -348,10 +347,11 @@ static int builtin_ulimit(parser_t &parser, io_streams_t &streams, wchar_t **arg
case 0: case 0:
if (long_options[opt_index].flag != 0) if (long_options[opt_index].flag != 0)
break; break;
streams.err.append_format(BUILTIN_ERR_UNKNOWN, append_format(stderr_buffer,
BUILTIN_ERR_UNKNOWN,
argv[0], argv[0],
long_options[opt_index].name); long_options[opt_index].name);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
@@ -415,40 +415,40 @@ static int builtin_ulimit(parser_t &parser, io_streams_t &streams, wchar_t **arg
#endif #endif
case L'h': case L'h':
builtin_print_help(parser, streams, argv[0], streams.out); builtin_print_help(parser, argv[0], stdout_buffer);
return 0; return 0;
case L'?': case L'?':
builtin_unknown_option(parser, streams, argv[0], argv[w.woptind-1]); builtin_unknown_option(parser, argv[0], argv[woptind-1]);
return 1; return 1;
} }
} }
if (report_all) if (report_all)
{ {
if (argc - w.woptind == 0) if (argc - woptind == 0)
{ {
print_all(hard, streams); print_all(hard);
} }
else else
{ {
streams.err.append(argv[0]); stderr_buffer.append(argv[0]);
streams.err.append(L": Too many arguments\n"); stderr_buffer.append(L": Too many arguments\n");
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
return 0; return 0;
} }
switch (argc - w.woptind) switch (argc - woptind)
{ {
case 0: case 0:
{ {
/* /*
Show current limit value Show current limit value
*/ */
print(what, hard, streams); print(what, hard);
break; break;
} }
@@ -468,41 +468,42 @@ static int builtin_ulimit(parser_t &parser, io_streams_t &streams, wchar_t **arg
hard=soft=1; hard=soft=1;
} }
if (wcscasecmp(argv[w.woptind], L"unlimited")==0) if (wcscasecmp(argv[woptind], L"unlimited")==0)
{ {
new_limit = RLIM_INFINITY; new_limit = RLIM_INFINITY;
} }
else if (wcscasecmp(argv[w.woptind], L"hard")==0) else if (wcscasecmp(argv[woptind], L"hard")==0)
{ {
new_limit = get(what, 1); new_limit = get(what, 1);
} }
else if (wcscasecmp(argv[w.woptind], L"soft")==0) else if (wcscasecmp(argv[woptind], L"soft")==0)
{ {
new_limit = get(what, soft); new_limit = get(what, soft);
} }
else else
{ {
errno=0; errno=0;
new_limit = wcstol(argv[w.woptind], &end, 10); new_limit = wcstol(argv[woptind], &end, 10);
if (errno || *end) if (errno || *end)
{ {
streams.err.append_format(L"%ls: Invalid limit '%ls'\n", append_format(stderr_buffer,
L"%ls: Invalid limit '%ls'\n",
argv[0], argv[0],
argv[w.woptind]); argv[woptind]);
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }
new_limit *= get_multiplier(what); new_limit *= get_multiplier(what);
} }
return set(what, hard, soft, new_limit, streams); return set(what, hard, soft, new_limit);
} }
default: default:
{ {
streams.err.append(argv[0]); stderr_buffer.append(argv[0]);
streams.err.append(L": Too many arguments\n"); stderr_buffer.append(L": Too many arguments\n");
builtin_print_help(parser, streams, argv[0], streams.err); builtin_print_help(parser, argv[0], stderr_buffer);
return 1; return 1;
} }

View File

@@ -1,15 +1,12 @@
// Color class implementation. /** \file color.cpp Color class implementation
*/
#include "color.h" #include "color.h"
#include "fallback.h" // IWYU pragma: keep #include "fallback.h"
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <wchar.h>
#include <cstddef>
bool rgb_color_t::try_parse_special(const wcstring &special) bool rgb_color_t::try_parse_special(const wcstring &special)
{ {
memset(&data, 0, sizeof data); bzero(&data, sizeof data);
const wchar_t *name = special.c_str(); const wchar_t *name = special.c_str();
if (! wcscasecmp(name, L"normal")) if (! wcscasecmp(name, L"normal"))
{ {
@@ -19,6 +16,10 @@ bool rgb_color_t::try_parse_special(const wcstring &special)
{ {
this->type = type_reset; this->type = type_reset;
} }
else if (! wcscasecmp(name, L"ignore"))
{
this->type = type_ignore;
}
else else
{ {
this->type = type_none; this->type = type_none;
@@ -101,7 +102,7 @@ static unsigned char convert_color(const unsigned char rgb[3], const uint32_t *c
bool rgb_color_t::try_parse_rgb(const wcstring &name) bool rgb_color_t::try_parse_rgb(const wcstring &name)
{ {
memset(&data, 0, sizeof data); bzero(&data, sizeof data);
/* We support the following style of rgb formats (case insensitive): /* We support the following style of rgb formats (case insensitive):
#FA3 #FA3
#F3A035 #F3A035
@@ -124,7 +125,7 @@ bool rgb_color_t::try_parse_rgb(const wcstring &name)
{ {
int val = parse_hex_digit(name.at(digit_idx++)); int val = parse_hex_digit(name.at(digit_idx++));
if (val < 0) break; if (val < 0) break;
data.color.rgb[i] = val*16+val; data.rgb[i] = val*16+val;
} }
success = (i == 3); success = (i == 3);
} }
@@ -136,7 +137,7 @@ bool rgb_color_t::try_parse_rgb(const wcstring &name)
int hi = parse_hex_digit(name.at(digit_idx++)); int hi = parse_hex_digit(name.at(digit_idx++));
int lo = parse_hex_digit(name.at(digit_idx++)); int lo = parse_hex_digit(name.at(digit_idx++));
if (lo < 0 || hi < 0) break; if (lo < 0 || hi < 0) break;
data.color.rgb[i] = hi*16+lo; data.rgb[i] = hi*16+lo;
} }
success = (i == 3); success = (i == 3);
} }
@@ -154,7 +155,7 @@ struct named_color_t
unsigned char rgb[3]; unsigned char rgb[3];
}; };
static const named_color_t named_colors[] = static const named_color_t named_colors[11] =
{ {
{L"black", 0, {0, 0, 0}}, {L"black", 0, {0, 0, 0}},
{L"red", 1, {0xFF, 0, 0}}, {L"red", 1, {0xFF, 0, 0}},
@@ -165,40 +166,25 @@ static const named_color_t named_colors[] =
{L"magenta", 5, {0xFF, 0, 0xFF}}, {L"magenta", 5, {0xFF, 0, 0xFF}},
{L"purple", 5, {0xFF, 0, 0xFF}}, {L"purple", 5, {0xFF, 0, 0xFF}},
{L"cyan", 6, {0, 0xFF, 0xFF}}, {L"cyan", 6, {0, 0xFF, 0xFF}},
{L"grey", 7, {0xE5, 0xE5, 0xE5}}, {L"white", 7, {0xFF, 0xFF, 0xFF}},
{L"brgrey", 8, {0x55, 0x55, 0x55}}, {L"normal", 8, {0xFF, 0xFF, 0XFF}}
{L"brred", 9, {0xFF, 0x55, 0x55}},
{L"brgreen", 10, {0x55, 0xFF, 0x55}},
{L"brbrown", 11, {0xFF, 0xFF, 0x55}},
{L"bryellow", 11, {0xFF, 0xFF, 0x55}},
{L"brblue", 12, {0x55, 0x55, 0xFF}},
{L"brmagenta", 13, {0xFF, 0x55, 0xFF}},
{L"brpurple", 13, {0xFF, 0x55, 0xFF}},
{L"brcyan", 14, {0x55, 0xFF, 0xFF}},
{L"white", 15, {0xFF, 0xFF, 0xFF}},
}; };
wcstring_list_t rgb_color_t::named_color_names(void) wcstring_list_t rgb_color_t::named_color_names(void)
{ {
size_t count = sizeof named_colors / sizeof *named_colors; size_t count = sizeof named_colors / sizeof *named_colors;
wcstring_list_t result; wcstring_list_t result;
result.reserve(1 + count); result.reserve(count);
for (size_t i=0; i < count; i++) for (size_t i=0; i < count; i++)
{ {
result.push_back(named_colors[i].name); result.push_back(named_colors[i].name);
} }
// "normal" isn't really a color and does not have a color palette index or
// RGB value. Therefore, it does not appear in the named_colors table.
// However, it is a legitimate color name for the "set_color" command so
// include it in the publicly known list of colors. This is primarily so it
// appears in the output of "set_color --print-colors".
result.push_back(L"normal");
return result; return result;
} }
bool rgb_color_t::try_parse_named(const wcstring &str) bool rgb_color_t::try_parse_named(const wcstring &str)
{ {
memset(&data, 0, sizeof data); bzero(&data, sizeof data);
size_t max = sizeof named_colors / sizeof *named_colors; size_t max = sizeof named_colors / sizeof *named_colors;
for (size_t idx=0; idx < max; idx++) for (size_t idx=0; idx < max; idx++)
{ {
@@ -234,22 +220,22 @@ rgb_color_t rgb_color_t::normal()
{ {
return rgb_color_t(type_normal); return rgb_color_t(type_normal);
} }
rgb_color_t rgb_color_t::reset() rgb_color_t rgb_color_t::reset()
{ {
return rgb_color_t(type_reset); return rgb_color_t(type_reset);
} }
rgb_color_t rgb_color_t::ignore()
{
return rgb_color_t(type_ignore);
}
rgb_color_t rgb_color_t::none() rgb_color_t rgb_color_t::none()
{ {
return rgb_color_t(type_none); return rgb_color_t(type_none);
} }
rgb_color_t rgb_color_t::white() rgb_color_t rgb_color_t::white()
{ {
return rgb_color_t(type_named, 7); return rgb_color_t(type_named, 7);
} }
rgb_color_t rgb_color_t::black() rgb_color_t rgb_color_t::black()
{ {
return rgb_color_t(type_named, 0); return rgb_color_t(type_named, 0);
@@ -312,13 +298,7 @@ static unsigned char term256_color_for_rgb(const unsigned char rgb[3])
unsigned char rgb_color_t::to_term256_index() const unsigned char rgb_color_t::to_term256_index() const
{ {
assert(type == type_rgb); assert(type == type_rgb);
return term256_color_for_rgb(data.color.rgb); return term256_color_for_rgb(data.rgb);
}
color24_t rgb_color_t::to_color24() const
{
assert(type == type_rgb);
return data.color;
} }
unsigned char rgb_color_t::to_name_index() const unsigned char rgb_color_t::to_name_index() const
@@ -330,7 +310,7 @@ unsigned char rgb_color_t::to_name_index() const
} }
else if (type == type_rgb) else if (type == type_rgb)
{ {
return term8_color_for_rgb(data.color.rgb); return term8_color_for_rgb(data.rgb);
} }
else else
{ {
@@ -347,17 +327,17 @@ void rgb_color_t::parse(const wcstring &str)
if (! success) success = try_parse_rgb(str); if (! success) success = try_parse_rgb(str);
if (! success) if (! success)
{ {
memset(&this->data, 0, sizeof this->data); bzero(this->data.rgb, sizeof this->data.rgb);
this->type = type_none; this->type = type_none;
} }
} }
rgb_color_t::rgb_color_t(const wcstring &str) : type(), flags() rgb_color_t::rgb_color_t(const wcstring &str)
{ {
this->parse(str); this->parse(str);
} }
rgb_color_t::rgb_color_t(const std::string &str) : type(), flags() rgb_color_t::rgb_color_t(const std::string &str)
{ {
this->parse(str2wcstring(str)); this->parse(str2wcstring(str));
} }
@@ -371,11 +351,13 @@ wcstring rgb_color_t::description() const
case type_named: case type_named:
return format_string(L"named(%d: %ls)", (int)data.name_idx, name_for_color_idx(data.name_idx)); return format_string(L"named(%d: %ls)", (int)data.name_idx, name_for_color_idx(data.name_idx));
case type_rgb: case type_rgb:
return format_string(L"rgb(0x%02x%02x%02x)", data.color.rgb[0], data.color.rgb[1], data.color.rgb[2]); return format_string(L"rgb(0x%02x%02x%02x)", data.rgb[0], data.rgb[1], data.rgb[2]);
case type_reset: case type_reset:
return L"reset"; return L"reset";
case type_normal: case type_normal:
return L"normal"; return L"normal";
case type_ignore:
return L"ignore";
default: default:
abort(); abort();
return L""; return L"";

View File

@@ -1,16 +1,13 @@
// Color class. /** \file color.h Color class.
*/
#ifndef FISH_COLOR_H #ifndef FISH_COLOR_H
#define FISH_COLOR_H #define FISH_COLOR_H
#include <string.h> #include <stdint.h>
#include <string> #include <cstddef>
#include "config.h"
#include "common.h" #include "common.h"
/* 24 bit color */
struct color24_t
{
unsigned char rgb[3];
};
/* A type that represents a color. We work hard to keep it at a size of 4 bytes. */ /* A type that represents a color. We work hard to keep it at a size of 4 bytes. */
class rgb_color_t class rgb_color_t
@@ -23,7 +20,8 @@ class rgb_color_t
type_named, type_named,
type_rgb, type_rgb,
type_normal, type_normal,
type_reset type_reset,
type_ignore
}; };
unsigned char type:4; unsigned char type:4;
@@ -38,7 +36,7 @@ class rgb_color_t
union union
{ {
unsigned char name_idx; //0-10 unsigned char name_idx; //0-10
color24_t color; unsigned char rgb[3];
} data; } data;
/** Try parsing a special color name like "normal" */ /** Try parsing a special color name like "normal" */
@@ -77,9 +75,18 @@ class rgb_color_t
/** Returns the normal special color */ /** Returns the normal special color */
static rgb_color_t normal(); static rgb_color_t normal();
/** Returns the ignore special color */
static rgb_color_t ignore();
/** Returns the none special color */ /** Returns the none special color */
static rgb_color_t none(); static rgb_color_t none();
/** Returns whether the color is the ignore special color */
bool is_ignore(void) const
{
return type == type_ignore;
}
/** Returns whether the color is the normal special color */ /** Returns whether the color is the normal special color */
bool is_normal(void) const bool is_normal(void) const
{ {
@@ -122,12 +129,9 @@ class rgb_color_t
/** Returns the name index for the given color. Requires that the color be named or RGB. */ /** Returns the name index for the given color. Requires that the color be named or RGB. */
unsigned char to_name_index() const; unsigned char to_name_index() const;
/** Returns the term256 index for the given color. Requires that the color be RGB. */ /** Returns the term256 index for the given color. Requires that the color be named or RGB. */
unsigned char to_term256_index() const; unsigned char to_term256_index() const;
/** Returns the 24 bit color for the given color. Requires that the color be RGB. */
color24_t to_color24() const;
/** Returns whether the color is bold */ /** Returns whether the color is bold */
bool is_bold() const bool is_bold() const
{ {

File diff suppressed because it is too large Load Diff

View File

@@ -17,13 +17,10 @@
#include <vector> #include <vector>
#include <pthread.h> #include <pthread.h>
#include <string.h> #include <string.h>
#include <stdarg.h>
#include <stddef.h>
#include <sys/types.h>
#include <errno.h> #include <errno.h>
#include "config.h" #include <assert.h>
#include "fallback.h" #include "util.h"
/** /**
Avoid writing the type name twice in a common "static_cast-initialization". Avoid writing the type name twice in a common "static_cast-initialization".
@@ -31,76 +28,46 @@
*/ */
#define CAST_INIT(type, dst, src) type dst = static_cast<type >(src) #define CAST_INIT(type, dst, src) type dst = static_cast<type >(src)
class completion_t;
/* Common string type */ /* Common string type */
typedef std::wstring wcstring; typedef std::wstring wcstring;
typedef std::vector<wcstring> wcstring_list_t; typedef std::vector<wcstring> wcstring_list_t;
// Maximum number of bytes used by a single utf-8 character. /**
Maximum number of bytes used by a single utf-8 character
*/
#define MAX_UTF8_BYTES 6 #define MAX_UTF8_BYTES 6
// Highest legal ASCII value. /**
This is in the unicode private use area.
*/
#define ENCODE_DIRECT_BASE 0xf100
/**
Highest legal ascii value
*/
#define ASCII_MAX 127u #define ASCII_MAX 127u
// Highest legal 16-bit Unicode value. /**
#define UCS2_MAX 0xFFFFu Highest legal 16-bit unicode value
*/
#define UCS2_MAX 0xffffu
// Highest legal byte value. /**
#define BYTE_MAX 0xFFu Highest legal byte value
*/
#define BYTE_MAX 0xffu
// Unicode BOM value. /**
#define UTF8_BOM_WCHAR 0xFEFFu Escape special fish syntax characters like the semicolon
*/
#define UNESCAPE_SPECIAL 1
// Unicode replacement character. /**
#define REPLACEMENT_WCHAR 0xFFFDu Allow incomplete escape sequences
*/
// Use Unicode "noncharacters" for internal characters as much as we can. This #define UNESCAPE_INCOMPLETE 2
// gives us 32 "characters" for internal use that we can guarantee should not
// appear in our input stream. See http://www.unicode.org/faq/private_use.html.
#define RESERVED_CHAR_BASE 0xFDD0u
#define RESERVED_CHAR_END 0xFDF0u
// Split the available noncharacter values into two ranges to ensure there are
// no conflicts among the places we use these special characters.
#define EXPAND_RESERVED_BASE RESERVED_CHAR_BASE
#define EXPAND_RESERVED_END (EXPAND_RESERVED_BASE + 16)
#define WILDCARD_RESERVED_BASE EXPAND_RESERVED_END
#define WILDCARD_RESERVED_END (WILDCARD_RESERVED_BASE + 16)
// Make sure the ranges defined above don't exceed the range for noncharacters.
// This is to make sure we didn't do something stupid in subdividing the
// Unicode range for our needs.
#if WILDCARD_RESERVED_END > RESERVED_CHAR_END
#error
#endif
// These are in the Unicode private-use range. We really shouldn't use this
// range but have little choice in the matter given how our lexer/parser works.
// We can't use non-characters for these two ranges because there are only 66 of
// them and we need at least 256 + 64.
//
// If sizeof(wchar_t))==4 we could avoid using private-use chars; however, that
// would result in fish having different behavior on machines with 16 versus 32
// bit wchar_t. It's better that fish behave the same on both types of systems.
//
// Note: We don't use the highest 8 bit range (0xF800 - 0xF8FF) because we know
// of at least one use of a codepoint in that range: the Apple symbol (0xF8FF)
// on Mac OS X. See http://www.unicode.org/faq/private_use.html.
#define ENCODE_DIRECT_BASE 0xF600u
#define ENCODE_DIRECT_END (ENCODE_DIRECT_BASE + 256)
#define INPUT_COMMON_BASE 0xF700u
#define INPUT_COMMON_END (INPUT_COMMON_BASE + 64)
/* Flags for unescape_string functions */
enum
{
/* Default behavior */
UNESCAPE_DEFAULT = 0,
/* Escape special fish syntax characters like the semicolon */
UNESCAPE_SPECIAL = 1 << 0,
/* Allow incomplete escape sequences */
UNESCAPE_INCOMPLETE = 1 << 1
};
typedef unsigned int unescape_flags_t;
/* Flags for the escape() and escape_string() functions */ /* Flags for the escape() and escape_string() functions */
enum enum
@@ -116,47 +83,10 @@ enum
}; };
typedef unsigned int escape_flags_t; typedef unsigned int escape_flags_t;
/* Directions */
enum selection_direction_t
{
/* visual directions */
direction_north,
direction_east,
direction_south,
direction_west,
direction_page_north,
direction_page_south,
/* logical directions */
direction_next,
direction_prev,
/* special value that means deselect */
direction_deselect
};
inline bool selection_direction_is_cardinal(selection_direction_t dir)
{
switch (dir)
{
case direction_north:
case direction_page_north:
case direction_east:
case direction_page_south:
case direction_south:
case direction_west:
return true;
default:
return false;
}
}
/** /**
Helper macro for errors Helper macro for errors
*/ */
#define VOMIT_ON_FAILURE(a) do { if (0 != (a)) { VOMIT_ABORT(errno, #a); } } while (0) #define VOMIT_ON_FAILURE(a) do { if (0 != (a)) { int err = errno; fprintf(stderr, "%s failed on line %d in file %s: %d (%s)\n", #a, __LINE__, __FILE__, err, strerror(err)); abort(); }} while (0)
#define VOMIT_ON_FAILURE_NO_ERRNO(a) do { int err = (a); if (0 != err) { VOMIT_ABORT(err, #a); } } while (0)
#define VOMIT_ABORT(err, str) do { int code = (err); fprintf(stderr, "%s failed on line %d in file %s: %d (%s)\n", str, __LINE__, __FILE__, code, strerror(code)); abort(); } while(0)
/** Exits without invoking destructors (via _exit), useful for code after fork. */ /** Exits without invoking destructors (via _exit), useful for code after fork. */
void exit_without_destructors(int code) __attribute__((noreturn)); void exit_without_destructors(int code) __attribute__((noreturn));
@@ -184,7 +114,7 @@ extern int debug_level;
/** /**
Profiling flag. True if commands should be profiled. Profiling flag. True if commands should be profiled.
*/ */
extern bool g_profiling_active; extern char *profile;
/** /**
Name of the current program. Should be set at startup. Used by the Name of the current program. Should be set at startup. Used by the
@@ -192,10 +122,6 @@ extern bool g_profiling_active;
*/ */
extern const wchar_t *program_name; extern const wchar_t *program_name;
/* Variants of read() and write() that ignores return values, defeating a warning */
void read_ignore(int fd, void *buff, size_t count);
void write_ignore(int fd, const void *buff, size_t count);
/** /**
This macro is used to check that an input argument is not null. It This macro is used to check that an input argument is not null. It
is a bit lika a non-fatal form of assert. Instead of exit-ing on is a bit lika a non-fatal form of assert. Instead of exit-ing on
@@ -219,10 +145,10 @@ void write_ignore(int fd, const void *buff, size_t count);
*/ */
#define FATAL_EXIT() \ #define FATAL_EXIT() \
{ \ { \
char exit_read_buff; \ char exit_read_buff; \
show_stackframe(); \ show_stackframe(); \
read_ignore( 0, &exit_read_buff, 1 ); \ read( 0, &exit_read_buff, 1 ); \
exit_without_destructors( 1 ); \ exit_without_destructors( 1 ); \
} \ } \
@@ -267,7 +193,7 @@ void write_ignore(int fd, const void *buff, size_t count);
/** /**
Check if the specified string element is a part of the specified string list Check if the specified string element is a part of the specified string list
*/ */
#define contains( str, ... ) contains_internal( str, 0, __VA_ARGS__, NULL ) #define contains( str,... ) contains_internal( str, __VA_ARGS__, NULL )
/** /**
Print a stack trace to stderr Print a stack trace to stderr
@@ -317,81 +243,10 @@ bool string_prefixes_string(const wchar_t *proposed_prefix, const wcstring &valu
bool string_suffixes_string(const wcstring &proposed_suffix, const wcstring &value); bool string_suffixes_string(const wcstring &proposed_suffix, const wcstring &value);
bool string_suffixes_string(const wchar_t *proposed_suffix, const wcstring &value); bool string_suffixes_string(const wchar_t *proposed_suffix, const wcstring &value);
/** Test if a string prefixes another without regard to case. Returns true if a is a prefix of b */ /** Test if a string prefixes another without regard to case. Returns true if a is a prefix of b */
bool string_prefixes_string_case_insensitive(const wcstring &proposed_prefix, const wcstring &value); bool string_prefixes_string_case_insensitive(const wcstring &proposed_prefix, const wcstring &value);
enum fuzzy_match_type_t
{
/* We match the string exactly: FOOBAR matches FOOBAR */
fuzzy_match_exact = 0,
/* We match a prefix of the string: FO matches FOOBAR */
fuzzy_match_prefix,
/* We match the string exactly, but in a case insensitive way: foobar matches FOOBAR */
fuzzy_match_case_insensitive,
/* We match a prefix of the string, in a case insensitive way: foo matches FOOBAR */
fuzzy_match_prefix_case_insensitive,
/* We match a substring of the string: OOBA matches FOOBAR */
fuzzy_match_substring,
/* A subsequence match with insertions only: FBR matches FOOBAR */
fuzzy_match_subsequence_insertions_only,
/* We don't match the string */
fuzzy_match_none
};
/* Indicates where a match type requires replacing the entire token */
static inline bool match_type_requires_full_replacement(fuzzy_match_type_t t)
{
switch (t)
{
case fuzzy_match_exact:
case fuzzy_match_prefix:
return false;
default:
return true;
}
}
/* Indicates where a match shares a prefix with the string it matches */
static inline bool match_type_shares_prefix(fuzzy_match_type_t t)
{
switch (t)
{
case fuzzy_match_exact:
case fuzzy_match_prefix:
case fuzzy_match_case_insensitive:
case fuzzy_match_prefix_case_insensitive:
return true;
default:
return false;
}
}
/** Test if string is a fuzzy match to another */
struct string_fuzzy_match_t
{
enum fuzzy_match_type_t type;
/* Strength of the match. The value depends on the type. Lower is stronger. */
size_t match_distance_first;
size_t match_distance_second;
/* Constructor */
explicit string_fuzzy_match_t(enum fuzzy_match_type_t t, size_t distance_first = 0, size_t distance_second = 0);
/* Return -1, 0, 1 if this match is (respectively) better than, equal to, or worse than rhs */
int compare(const string_fuzzy_match_t &rhs) const;
};
/* Compute a fuzzy match for a string. If maximum_match is not fuzzy_match_none, limit the type to matches at or below that type. */
string_fuzzy_match_t string_fuzzy_match_string(const wcstring &string, const wcstring &match_against, fuzzy_match_type_t limit_type = fuzzy_match_none);
/** Test if a list contains a string using a linear search. */ /** Test if a list contains a string using a linear search. */
bool list_contains_string(const wcstring_list_t &list, const wcstring &str); bool list_contains_string(const wcstring_list_t &list, const wcstring &str);
@@ -418,11 +273,8 @@ void format_size_safe(char buff[128], unsigned long long sz);
void debug_safe(int level, const char *msg, const char *param1 = NULL, const char *param2 = NULL, const char *param3 = NULL, const char *param4 = NULL, const char *param5 = NULL, const char *param6 = NULL, const char *param7 = NULL, const char *param8 = NULL, const char *param9 = NULL, const char *param10 = NULL, const char *param11 = NULL, const char *param12 = NULL); void debug_safe(int level, const char *msg, const char *param1 = NULL, const char *param2 = NULL, const char *param3 = NULL, const char *param4 = NULL, const char *param5 = NULL, const char *param6 = NULL, const char *param7 = NULL, const char *param8 = NULL, const char *param9 = NULL, const char *param10 = NULL, const char *param11 = NULL, const char *param12 = NULL);
/** Writes out a long safely */ /** Writes out a long safely */
void format_long_safe(char buff[64], long val); void format_long_safe(char buff[128], long val);
void format_long_safe(wchar_t buff[64], long val); void format_long_safe(wchar_t buff[128], long val);
/** "Narrows" a wide character string. This just grabs any ASCII characters and trunactes. */
void narrow_string_safe(char buff[64], const wchar_t *s);
template<typename T> template<typename T>
@@ -478,17 +330,6 @@ inline wcstring to_string(const int &x)
return to_string(static_cast<long>(x)); return to_string(static_cast<long>(x));
} }
/* A hackish thing to simulate rvalue references in C++98.
The idea is that you can define a constructor to take a moved_ref<T> and then swap() out of it.
*/
template<typename T>
struct moved_ref
{
T &val;
explicit moved_ref(T &v) : val(v) { }
};
wchar_t **make_null_terminated_array(const wcstring_list_t &lst); wchar_t **make_null_terminated_array(const wcstring_list_t &lst);
char **make_null_terminated_array(const std::vector<std::string> &lst); char **make_null_terminated_array(const std::vector<std::string> &lst);
@@ -525,7 +366,7 @@ class null_terminated_array_t
public: public:
null_terminated_array_t() : array(NULL) { } null_terminated_array_t() : array(NULL) { }
explicit null_terminated_array_t(const string_list_t &argv) : array(make_null_terminated_array(argv)) null_terminated_array_t(const string_list_t &argv) : array(make_null_terminated_array(argv))
{ {
} }
@@ -554,24 +395,38 @@ class null_terminated_array_t
/* Helper function to convert from a null_terminated_array_t<wchar_t> to a null_terminated_array_t<char_t> */ /* Helper function to convert from a null_terminated_array_t<wchar_t> to a null_terminated_array_t<char_t> */
void convert_wide_array_to_narrow(const null_terminated_array_t<wchar_t> &arr, null_terminated_array_t<char> *output); void convert_wide_array_to_narrow(const null_terminated_array_t<wchar_t> &arr, null_terminated_array_t<char> *output);
bool is_forked_child(); /* Helper class to cache a narrow version of a wcstring in a malloc'd buffer, so that we can read it after fork() */
class narrow_string_rep_t
class mutex_lock_t
{ {
public: private:
pthread_mutex_t mutex; const char *str;
mutex_lock_t()
/* No copying */
narrow_string_rep_t &operator=(const narrow_string_rep_t &);
narrow_string_rep_t(const narrow_string_rep_t &x);
public:
~narrow_string_rep_t()
{ {
VOMIT_ON_FAILURE_NO_ERRNO(pthread_mutex_init(&mutex, NULL)); free((void *)str);
} }
~mutex_lock_t() narrow_string_rep_t() : str(NULL) {}
void set(const wcstring &s)
{ {
VOMIT_ON_FAILURE_NO_ERRNO(pthread_mutex_destroy(&mutex)); free((void *)str);
str = wcs2str(s.c_str());
}
const char *get() const
{
return str;
} }
}; };
bool is_forked_child();
/* Basic scoped lock class */ /* Basic scoped lock class */
class scoped_lock class scoped_lock
{ {
@@ -585,53 +440,10 @@ class scoped_lock
public: public:
void lock(void); void lock(void);
void unlock(void); void unlock(void);
explicit scoped_lock(pthread_mutex_t &mutex); scoped_lock(pthread_mutex_t &mutex);
explicit scoped_lock(mutex_lock_t &lock);
~scoped_lock(); ~scoped_lock();
}; };
class rwlock_t
{
public:
pthread_rwlock_t rwlock;
rwlock_t()
{
VOMIT_ON_FAILURE_NO_ERRNO(pthread_rwlock_init(&rwlock, NULL));
}
~rwlock_t()
{
VOMIT_ON_FAILURE_NO_ERRNO(pthread_rwlock_destroy(&rwlock));
}
};
/*
Scoped lock class for rwlocks
*/
class scoped_rwlock
{
pthread_rwlock_t *rwlock_obj;
bool locked;
bool locked_shared;
/* No copying */
scoped_rwlock &operator=(const scoped_lock &);
explicit scoped_rwlock(const scoped_lock &);
public:
void lock(void);
void unlock(void);
void lock_shared(void);
void unlock_shared(void);
/*
upgrade shared lock to exclusive.
equivalent to `lock.unlock_shared(); lock.lock();`
*/
void upgrade(void);
explicit scoped_rwlock(pthread_rwlock_t &rwlock, bool shared = false);
explicit scoped_rwlock(rwlock_t &rwlock, bool shared = false);
~scoped_rwlock();
};
/** /**
A scoped manager to save the current value of some variable, and optionally A scoped manager to save the current value of some variable, and optionally
@@ -648,7 +460,7 @@ class scoped_push
bool restored; bool restored;
public: public:
explicit scoped_push(T *r): ref(r), saved_value(*r), restored(false) scoped_push(T *r): ref(r), saved_value(*r), restored(false)
{ {
} }
@@ -699,14 +511,19 @@ wcstring vformat_string(const wchar_t *format, va_list va_orig);
void append_format(wcstring &str, const wchar_t *format, ...); void append_format(wcstring &str, const wchar_t *format, ...);
void append_formatv(wcstring &str, const wchar_t *format, va_list ap); void append_formatv(wcstring &str, const wchar_t *format, va_list ap);
/**
Returns a newly allocated wide character string array equivalent of
the specified multibyte character string array
*/
char **wcsv2strv(const wchar_t * const *in);
/** /**
Test if the given string is a valid variable name. Test if the given string is a valid variable name.
\return null if this is a valid name, and a pointer to the first invalid character otherwise \return null if this is a valid name, and a pointer to the first invalid character otherwise
*/ */
const wchar_t *wcsvarname(const wchar_t *str); wchar_t *wcsvarname(const wchar_t *str);
const wchar_t *wcsvarname(const wcstring &str);
/** /**
@@ -715,23 +532,21 @@ const wchar_t *wcsvarname(const wcstring &str);
\return null if this is a valid name, and a pointer to the first invalid character otherwise \return null if this is a valid name, and a pointer to the first invalid character otherwise
*/ */
const wchar_t *wcsfuncname(const wcstring &str); const wchar_t *wcsfuncname(const wchar_t *str);
/** /**
Test if the given string is valid in a variable name Test if the given string is valid in a variable name
\return true if this is a valid name, false otherwise \return 1 if this is a valid name, 0 otherwise
*/ */
bool wcsvarchr(wchar_t chr); int wcsvarchr(wchar_t chr);
/** /**
Convenience variants on fish_wcwswidth(). A wcswidth workalike. Fish uses this since the regular wcswidth seems flaky.
See fallback.h for the normal definitions.
*/ */
int fish_wcswidth(const wchar_t *str); int my_wcswidth(const wchar_t *c);
int fish_wcswidth(const wcstring& str);
/** /**
This functions returns the end of the quoted substring beginning at This functions returns the end of the quoted substring beginning at
@@ -767,8 +582,8 @@ wcstring wsetlocale(int category, const wchar_t *locale);
\return zero if needle is not found, of if needle is null, non-zero otherwise \return zero if needle is not found, of if needle is null, non-zero otherwise
*/ */
__sentinel bool contains_internal(const wchar_t *needle, int vararg_handle, ...); __sentinel bool contains_internal(const wchar_t *needle, ...);
__sentinel bool contains_internal(const wcstring &needle, int vararg_handle, ...); __sentinel bool contains_internal(const wcstring &needle, ...);
/** /**
Call read while blocking the SIGCHLD signal. Should only be called Call read while blocking the SIGCHLD signal. Should only be called
@@ -816,11 +631,11 @@ void debug(int level, const wchar_t *msg, ...);
replaced with \n, etc. replaced with \n, etc.
\param in The string to be escaped \param in The string to be escaped
\param flags Flags to control the escaping \param escape_all Whether all characters wich hold special meaning in fish (Pipe, semicolon, etc,) should be escaped, or only unprintable characters
\return The escaped string \return The escaped string, or 0 if there is not enough memory
*/ */
wcstring escape(const wchar_t *in, escape_flags_t flags); wchar_t *escape(const wchar_t *in, escape_flags_t flags);
wcstring escape_string(const wcstring &in, escape_flags_t flags); wcstring escape_string(const wcstring &in, escape_flags_t flags);
/** /**
@@ -829,17 +644,16 @@ wcstring escape_string(const wcstring &in, escape_flags_t flags);
character and a few more into constants which are defined in a character and a few more into constants which are defined in a
private use area of Unicode. This assumes wchar_t is a unicode private use area of Unicode. This assumes wchar_t is a unicode
character set. character set.
The result must be free()d. The original string is not modified. If
an invalid sequence is specified, 0 is returned.
*/ */
wchar_t *unescape(const wchar_t * in,
int escape_special);
/** Given a null terminated string starting with a backslash, read the escape as if it is unquoted, appending to result. Return the number of characters consumed, or 0 on error */ bool unescape_string(wcstring &str,
size_t read_unquoted_escape(const wchar_t *input, wcstring *result, bool allow_incomplete, bool unescape_special); int escape_special);
/** Unescapes a string in-place. A true result indicates the string was unescaped, a false result indicates the string was unmodified. */
bool unescape_string_in_place(wcstring *str, unescape_flags_t escape_special);
/** Unescapes a string, returning the unescaped value by reference. On failure, the output is set to an empty string. */
bool unescape_string(const wchar_t *input, wcstring *output, unescape_flags_t escape_special);
bool unescape_string(const wcstring &input, wcstring *output, unescape_flags_t escape_special);
/** /**
@@ -867,10 +681,10 @@ int common_get_height();
void common_handle_winch(int signal); void common_handle_winch(int signal);
/** /**
Write the given paragraph of output, redoing linebreaks to fit Write paragraph of output to the specified stringbuffer, and redo
the current screen. the linebreaks to fit the current screen.
*/ */
wcstring reformat_for_screen(const wcstring &msg); void write_screen(const wcstring &msg, wcstring &buff);
/** /**
Tokenize the specified string into the specified wcstring_list_t. Tokenize the specified string into the specified wcstring_list_t.
@@ -924,12 +738,11 @@ void assert_is_not_forked_child(const char *who);
#define ASSERT_IS_NOT_FORKED_CHILD_TRAMPOLINE(x) assert_is_not_forked_child(x) #define ASSERT_IS_NOT_FORKED_CHILD_TRAMPOLINE(x) assert_is_not_forked_child(x)
#define ASSERT_IS_NOT_FORKED_CHILD() ASSERT_IS_NOT_FORKED_CHILD_TRAMPOLINE(__FUNCTION__) #define ASSERT_IS_NOT_FORKED_CHILD() ASSERT_IS_NOT_FORKED_CHILD_TRAMPOLINE(__FUNCTION__)
/** Macro to help suppress potentially unused variable warnings */
#define USE(var) (void)(var)
extern "C" { extern "C" {
__attribute__((noinline)) void debug_thread_error(void); __attribute__((noinline)) void debug_thread_error(void);
} }
/** Return the path of an appropriate runtime data directory */
std::string common_get_runtime_path();
#endif #endif

2102
complete.cpp Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -12,9 +12,10 @@
*/ */
#define FISH_COMPLETE_H #define FISH_COMPLETE_H
#include <vector>
#include <stdint.h>
#include <wchar.h>
#include "util.h"
#include "common.h" #include "common.h"
/** /**
* Use all completions * Use all completions
@@ -30,7 +31,7 @@
#define NO_COMMON 2 #define NO_COMMON 2
/** /**
* Only use the argument list specifies with completion after * Only use the argument list specifies with completion after
* option. This is the same as (NO_FILES | NO_COMMON) * option. This is the same as (NO_FILES & NO_COMMON)
*/ */
#define EXCLUSIVE 3 #define EXCLUSIVE 3
@@ -48,6 +49,18 @@
*/ */
#define COMPLETE_SEP L'\004' #define COMPLETE_SEP L'\004'
/**
* Separator between completion and description
*/
#define COMPLETE_SEP_STR L"\004"
/**
* Separator between completion items in fish_pager. This is used for
* completion grouping, e.g. when putting completions with the same
* descriptions on the same line.
*/
#define COMPLETE_ITEM_SEP L'\uf500'
/** /**
* Character that separates the completion and description on * Character that separates the completion and description on
* programmable completions * programmable completions
@@ -62,11 +75,16 @@ enum
*/ */
COMPLETE_NO_SPACE = 1 << 0, COMPLETE_NO_SPACE = 1 << 0,
/** This completion is case insensitive. */
COMPLETE_CASE_INSENSITIVE = 1 << 1,
/** This is not the suffix of a token, but replaces it entirely */ /** This is not the suffix of a token, but replaces it entirely */
COMPLETE_REPLACES_TOKEN = 1 << 2, COMPLETE_REPLACES_TOKEN = 1 << 2,
/** This completion may or may not want a space at the end - guess by /**
checking the last character of the completion. */ This completion may or may not want a space at the end - guess by
checking the last character of the completion.
*/
COMPLETE_AUTO_SPACE = 1 << 3, COMPLETE_AUTO_SPACE = 1 << 3,
/** This completion should be inserted as-is, without escaping. */ /** This completion should be inserted as-is, without escaping. */
@@ -89,15 +107,16 @@ class completion_t
/* Destructor. Not inlining it saves code size. */ /* Destructor. Not inlining it saves code size. */
~completion_t(); ~completion_t();
/** The completion string */ /**
The completion string
*/
wcstring completion; wcstring completion;
/** The description for this completion */ /**
The description for this completion
*/
wcstring description; wcstring description;
/** The type of fuzzy match */
string_fuzzy_match_t match;
/** /**
Flags determining the completion behaviour. Flags determining the completion behaviour.
@@ -108,26 +127,24 @@ class completion_t
The COMPLETE_NO_CASE can be used to signal that this completion The COMPLETE_NO_CASE can be used to signal that this completion
is case insensitive. is case insensitive.
*/ */
complete_flags_t flags; int flags;
bool is_case_insensitive() const
{
return !!(flags & COMPLETE_CASE_INSENSITIVE);
}
/* Construction. Note: defining these so that they are not inlined reduces the executable size. */ /* Construction. Note: defining these so that they are not inlined reduces the executable size. */
explicit completion_t(const wcstring &comp, const wcstring &desc = wcstring(), string_fuzzy_match_t match = string_fuzzy_match_t(fuzzy_match_exact), complete_flags_t flags_val = 0); completion_t(const wcstring &comp, const wcstring &desc = L"", int flags_val = 0);
completion_t(const completion_t &); completion_t(const completion_t &);
completion_t &operator=(const completion_t &); completion_t &operator=(const completion_t &);
/* Compare two completions. No operating overlaoding to make this always explicit (there's potentially multiple ways to compare completions). */ /* The following are needed for sorting and uniquing completions */
bool operator < (const completion_t& rhs) const;
/* "Naturally less than" means in a natural ordering, where digits are treated as numbers. For example, foo10 is naturally greater than foo2 (but alphabetically less than it) */ bool operator == (const completion_t& rhs) const;
static bool is_naturally_less_than(const completion_t &a, const completion_t &b); bool operator != (const completion_t& rhs) const;
static bool is_alphabetically_equal_to(const completion_t &a, const completion_t &b);
/* If this completion replaces the entire token, prepend a prefix. Otherwise do nothing. */
void prepend_token_prefix(const wcstring &prefix);
}; };
/** Sorts and remove any duplicate completions in the completion list, then puts them in priority order. */
void completions_sort_and_prioritize(std::vector<completion_t> *comps);
enum enum
{ {
COMPLETION_REQUEST_DEFAULT = 0, COMPLETION_REQUEST_DEFAULT = 0,
@@ -137,6 +154,12 @@ enum
}; };
typedef uint32_t completion_request_flags_t; typedef uint32_t completion_request_flags_t;
/** Given a list of completions, returns a list of their completion fields */
wcstring_list_t completions_to_wcstring_list(const std::vector<completion_t> &completions);
/** Sorts a list of completions */
void sort_completions(std::vector<completion_t> &completions);
/** /**
Add a completion. Add a completion.
@@ -182,17 +205,11 @@ typedef uint32_t completion_request_flags_t;
If \c condition is empty, the completion is always used. If \c condition is empty, the completion is always used.
\param flags A set of completion flags \param flags A set of completion flags
*/ */
enum complete_option_type_t
{
option_type_args_only, // no option
option_type_short, // -x
option_type_single_long, // -foo
option_type_double_long // --foo
};
void complete_add(const wchar_t *cmd, void complete_add(const wchar_t *cmd,
bool cmd_is_path, bool cmd_is_path,
const wcstring &option, wchar_t short_opt,
complete_option_type_t option_type, const wchar_t *long_opt,
int long_mode,
int result_mode, int result_mode,
const wchar_t *condition, const wchar_t *condition,
const wchar_t *comp, const wchar_t *comp,
@@ -208,26 +225,27 @@ void complete_set_authoritative(const wchar_t *cmd, bool cmd_type, bool authorit
/** /**
Remove a previously defined completion Remove a previously defined completion
*/ */
void complete_remove(const wcstring &cmd, void complete_remove(const wchar_t *cmd,
bool cmd_is_path, bool cmd_is_path,
const wcstring &option, wchar_t short_opt,
complete_option_type_t type); const wchar_t *long_opt);
/** Removes all completions for a given command */
void complete_remove_all(const wcstring &cmd, bool cmd_is_path);
/** Find all completions of the command cmd, insert them into out. /** Find all completions of the command cmd, insert them into out. If to_load is
* not NULL, append all commands that we would autoload, but did not (presumably
* because this is not the main thread)
*/ */
class env_vars_snapshot_t;
void complete(const wcstring &cmd, void complete(const wcstring &cmd,
std::vector<completion_t> *out_comps, std::vector<completion_t> &comp,
completion_request_flags_t flags, completion_request_flags_t flags,
const env_vars_snapshot_t &vars); wcstring_list_t *to_load = NULL);
/** /**
Return a list of all current completions. Print a list of all current completions into the string.
\param out The string to write completions to
*/ */
wcstring complete_print(); void complete_print(wcstring &out);
/** /**
Tests if the specified option is defined for the specified command Tests if the specified option is defined for the specified command
@@ -246,6 +264,19 @@ bool complete_is_valid_argument(const wcstring &str,
const wcstring &arg); const wcstring &arg);
/**
Load command-specific completions for the specified command. This
is done automatically whenever completing any given command, so
there is no need to call this except in the case of completions
with internal dependencies.
\param cmd the command for which to load command-specific completions
\param reload should the commands completions be reloaded, even if they where
previously loaded. (This is set to true on actual completions, so that
changed completion are updated in running shells)
*/
void complete_load(const wcstring &cmd, bool reload);
/** /**
Create a new completion entry Create a new completion entry
@@ -255,17 +286,9 @@ bool complete_is_valid_argument(const wcstring &str,
\param flags completion flags \param flags completion flags
*/ */
void append_completion(std::vector<completion_t> *completions, const wcstring &comp, const wcstring &desc = wcstring(), int flags = 0, string_fuzzy_match_t match = string_fuzzy_match_t(fuzzy_match_exact)); void append_completion(std::vector<completion_t> &completions, const wcstring &comp, const wcstring &desc = L"", int flags = 0);
/* Function used for testing */ /* Function used for testing */
void complete_set_variable_names(const wcstring_list_t *names); void complete_set_variable_names(const wcstring_list_t *names);
/* Support for "wrap targets." A wrap target is a command that completes liek another command. The target chain is the sequence of wraps (A wraps B wraps C...). Any loops in the chain are silently ignored. */
bool complete_add_wrapper(const wcstring &command, const wcstring &wrap_target);
bool complete_remove_wrapper(const wcstring &command, const wcstring &wrap_target);
wcstring_list_t complete_get_wrap_chain(const wcstring &command);
/* Wonky interface: returns all wraps. Even-values are the commands, odd values are the targets. */
wcstring_list_t complete_get_wrap_pairs();
#endif #endif

842
config.guess vendored

File diff suppressed because it is too large Load Diff

423
config.sub vendored
View File

@@ -1,40 +1,44 @@
#! /bin/sh #! /bin/sh
# Configuration validation subroutine script. # Configuration validation subroutine script.
# Copyright 1992-2015 Free Software Foundation, Inc. # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
# 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation,
# Inc.
timestamp='2015-03-08' timestamp='2006-02-27'
# This file is free software; you can redistribute it and/or modify it # This file is (in principle) common to ALL GNU software.
# under the terms of the GNU General Public License as published by # The presence of a machine in this file suggests that SOME GNU software
# the Free Software Foundation; either version 3 of the License, or # can handle that machine. It does not imply ALL GNU software can.
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, but # This program is distributed in the hope that it will be useful,
# WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>. # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
# 02110-1301, USA.
# #
# As a special exception to the GNU General Public License, if you # As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a # distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under # configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that # the same distribution terms that you use for the rest of that program.
# program. This Exception is an additional permission under section 7
# of the GNU General Public License, version 3 ("GPLv3").
# Please send patches to <config-patches@gnu.org>. # Please send patches to <config-patches@gnu.org>. Submit a context
# diff and a properly formatted ChangeLog entry.
# #
# Configuration subroutine to validate and canonicalize a configuration type. # Configuration subroutine to validate and canonicalize a configuration type.
# Supply the specified configuration type as an argument. # Supply the specified configuration type as an argument.
# If it is invalid, we print an error message on stderr and exit with code 1. # If it is invalid, we print an error message on stderr and exit with code 1.
# Otherwise, we print the canonical config type on stdout and succeed. # Otherwise, we print the canonical config type on stdout and succeed.
# You can get the latest version of this script from:
# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
# This file is supposed to be the same for all GNU packages # This file is supposed to be the same for all GNU packages
# and recognize all the CPU types, system types and aliases # and recognize all the CPU types, system types and aliases
# that are meaningful with *any* GNU software. # that are meaningful with *any* GNU software.
@@ -68,7 +72,8 @@ Report bugs and patches to <config-patches@gnu.org>."
version="\ version="\
GNU config.sub ($timestamp) GNU config.sub ($timestamp)
Copyright 1992-2015 Free Software Foundation, Inc. Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
@@ -115,18 +120,12 @@ esac
# Here we must recognize all the valid KERNEL-OS combinations. # Here we must recognize all the valid KERNEL-OS combinations.
maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
case $maybe_os in case $maybe_os in
nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \ nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* | \
linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \ uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | \
knetbsd*-gnu* | netbsd*-gnu* | netbsd*-eabi* | \
kopensolaris*-gnu* | \
storm-chaos* | os2-emx* | rtmk-nova*) storm-chaos* | os2-emx* | rtmk-nova*)
os=-$maybe_os os=-$maybe_os
basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
;; ;;
android-linux)
os=-linux-android
basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown
;;
*) *)
basic_machine=`echo $1 | sed 's/-[^-]*$//'` basic_machine=`echo $1 | sed 's/-[^-]*$//'`
if [ $basic_machine != $1 ] if [ $basic_machine != $1 ]
@@ -149,13 +148,10 @@ case $os in
-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
-apple | -axis | -knuth | -cray | -microblaze*) -apple | -axis | -knuth | -cray)
os= os=
basic_machine=$1 basic_machine=$1
;; ;;
-bluegene*)
os=-cnk
;;
-sim | -cisco | -oki | -wec | -winbond) -sim | -cisco | -oki | -wec | -winbond)
os= os=
basic_machine=$1 basic_machine=$1
@@ -170,10 +166,10 @@ case $os in
os=-chorusos os=-chorusos
basic_machine=$1 basic_machine=$1
;; ;;
-chorusrdb) -chorusrdb)
os=-chorusrdb os=-chorusrdb
basic_machine=$1 basic_machine=$1
;; ;;
-hiux*) -hiux*)
os=-hiuxwe2 os=-hiuxwe2
;; ;;
@@ -218,12 +214,6 @@ case $os in
-isc*) -isc*)
basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
;; ;;
-lynx*178)
os=-lynxos178
;;
-lynx*5)
os=-lynxos5
;;
-lynx*) -lynx*)
os=-lynxos os=-lynxos
;; ;;
@@ -248,90 +238,60 @@ case $basic_machine in
# Some are omitted here because they have special meanings below. # Some are omitted here because they have special meanings below.
1750a | 580 \ 1750a | 580 \
| a29k \ | a29k \
| aarch64 | aarch64_be \
| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
| am33_2.0 \ | am33_2.0 \
| arc | arceb \ | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \
| arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \
| avr | avr32 \
| be32 | be64 \
| bfin \ | bfin \
| c4x | c8051 | clipper \ | c4x | clipper \
| d10v | d30v | dlx | dsp16xx \ | d10v | d30v | dlx | dsp16xx \
| e2k | epiphany \ | fr30 | frv \
| fido | fr30 | frv | ft32 \
| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
| hexagon \
| i370 | i860 | i960 | ia64 \ | i370 | i860 | i960 | ia64 \
| ip2k | iq2000 \ | ip2k | iq2000 \
| k1om \ | m32r | m32rle | m68000 | m68k | m88k | maxq | mb | microblaze | mcore \
| le32 | le64 \
| lm32 \
| m32c | m32r | m32rle | m68000 | m68k | m88k \
| maxq | mb | microblaze | microblazeel | mcore | mep | metag \
| mips | mipsbe | mipseb | mipsel | mipsle \ | mips | mipsbe | mipseb | mipsel | mipsle \
| mips16 \ | mips16 \
| mips64 | mips64el \ | mips64 | mips64el \
| mips64octeon | mips64octeonel \
| mips64orion | mips64orionel \
| mips64r5900 | mips64r5900el \
| mips64vr | mips64vrel \ | mips64vr | mips64vrel \
| mips64orion | mips64orionel \
| mips64vr4100 | mips64vr4100el \ | mips64vr4100 | mips64vr4100el \
| mips64vr4300 | mips64vr4300el \ | mips64vr4300 | mips64vr4300el \
| mips64vr5000 | mips64vr5000el \ | mips64vr5000 | mips64vr5000el \
| mips64vr5900 | mips64vr5900el \ | mips64vr5900 | mips64vr5900el \
| mipsisa32 | mipsisa32el \ | mipsisa32 | mipsisa32el \
| mipsisa32r2 | mipsisa32r2el \ | mipsisa32r2 | mipsisa32r2el \
| mipsisa32r6 | mipsisa32r6el \
| mipsisa64 | mipsisa64el \ | mipsisa64 | mipsisa64el \
| mipsisa64r2 | mipsisa64r2el \ | mipsisa64r2 | mipsisa64r2el \
| mipsisa64r6 | mipsisa64r6el \
| mipsisa64sb1 | mipsisa64sb1el \ | mipsisa64sb1 | mipsisa64sb1el \
| mipsisa64sr71k | mipsisa64sr71kel \ | mipsisa64sr71k | mipsisa64sr71kel \
| mipsr5900 | mipsr5900el \
| mipstx39 | mipstx39el \ | mipstx39 | mipstx39el \
| mn10200 | mn10300 \ | mn10200 | mn10300 \
| moxie \
| mt \ | mt \
| msp430 \ | msp430 \
| nds32 | nds32le | nds32be \ | nios | nios2 \
| nios | nios2 | nios2eb | nios2el \
| ns16k | ns32k \ | ns16k | ns32k \
| open8 | or1k | or1knd | or32 \ | or32 \
| pdp10 | pdp11 | pj | pjl \ | pdp10 | pdp11 | pj | pjl \
| powerpc | powerpc64 | powerpc64le | powerpcle \ | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \
| pyramid \ | pyramid \
| riscv32 | riscv64 \ | sh | sh[1234] | sh[24]a | sh[23]e | sh[34]eb | shbe | shle | sh[1234]le | sh3ele \
| rl78 | rx \
| score \
| sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
| sh64 | sh64le \ | sh64 | sh64le \
| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
| sparcv8 | sparcv9 | sparcv9b | sparcv9v \ | sparcv8 | sparcv9 | sparcv9b | sparcv9v \
| spu \ | strongarm \
| tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \ | tahoe | thumb | tic4x | tic80 | tron \
| ubicom32 \ | v850 | v850e \
| v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
| visium \
| we32k \ | we32k \
| x86 | xc16x | xstormy16 | xtensa \ | x86 | xscale | xscalee[bl] | xstormy16 | xtensa \
| z8k | z80) | z8k)
basic_machine=$basic_machine-unknown basic_machine=$basic_machine-unknown
;; ;;
c54x) m32c)
basic_machine=tic54x-unknown basic_machine=$basic_machine-unknown
;; ;;
c55x) m6811 | m68hc11 | m6812 | m68hc12)
basic_machine=tic55x-unknown # Motorola 68HC11/12.
;;
c6x)
basic_machine=tic6x-unknown
;;
leon|leon[3-9])
basic_machine=sparc-$basic_machine
;;
m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip)
basic_machine=$basic_machine-unknown basic_machine=$basic_machine-unknown
os=-none os=-none
;; ;;
@@ -341,21 +301,6 @@ case $basic_machine in
basic_machine=mt-unknown basic_machine=mt-unknown
;; ;;
strongarm | thumb | xscale)
basic_machine=arm-unknown
;;
xgate)
basic_machine=$basic_machine-unknown
os=-none
;;
xscaleeb)
basic_machine=armeb-unknown
;;
xscaleel)
basic_machine=armel-unknown
;;
# We use `pc' rather than `unknown' # We use `pc' rather than `unknown'
# because (1) that's what they normally are, and # because (1) that's what they normally are, and
# (2) the word "unknown" tends to confuse beginning users. # (2) the word "unknown" tends to confuse beginning users.
@@ -370,87 +315,66 @@ case $basic_machine in
# Recognize the basic CPU types with company name. # Recognize the basic CPU types with company name.
580-* \ 580-* \
| a29k-* \ | a29k-* \
| aarch64-* | aarch64_be-* \
| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
| alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
| arm-* | armbe-* | armle-* | armeb-* | armv*-* \ | arm-* | armbe-* | armle-* | armeb-* | armv*-* \
| avr-* | avr32-* \ | avr-* \
| be32-* | be64-* \
| bfin-* | bs2000-* \ | bfin-* | bs2000-* \
| c[123]* | c30-* | [cjt]90-* | c4x-* \ | c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \
| c8051-* | clipper-* | craynv-* | cydra-* \ | clipper-* | craynv-* | cydra-* \
| d10v-* | d30v-* | dlx-* \ | d10v-* | d30v-* | dlx-* \
| e2k-* | elxsi-* \ | elxsi-* \
| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ | f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \
| h8300-* | h8500-* \ | h8300-* | h8500-* \
| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
| hexagon-* \
| i*86-* | i860-* | i960-* | ia64-* \ | i*86-* | i860-* | i960-* | ia64-* \
| ip2k-* | iq2000-* \ | ip2k-* | iq2000-* \
| k1om-* \ | m32r-* | m32rle-* \
| le32-* | le64-* \
| lm32-* \
| m32c-* | m32r-* | m32rle-* \
| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
| m88110-* | m88k-* | maxq-* | mcore-* | metag-* \ | m88110-* | m88k-* | maxq-* | mcore-* \
| microblaze-* | microblazeel-* \
| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
| mips16-* \ | mips16-* \
| mips64-* | mips64el-* \ | mips64-* | mips64el-* \
| mips64octeon-* | mips64octeonel-* \
| mips64orion-* | mips64orionel-* \
| mips64r5900-* | mips64r5900el-* \
| mips64vr-* | mips64vrel-* \ | mips64vr-* | mips64vrel-* \
| mips64orion-* | mips64orionel-* \
| mips64vr4100-* | mips64vr4100el-* \ | mips64vr4100-* | mips64vr4100el-* \
| mips64vr4300-* | mips64vr4300el-* \ | mips64vr4300-* | mips64vr4300el-* \
| mips64vr5000-* | mips64vr5000el-* \ | mips64vr5000-* | mips64vr5000el-* \
| mips64vr5900-* | mips64vr5900el-* \ | mips64vr5900-* | mips64vr5900el-* \
| mipsisa32-* | mipsisa32el-* \ | mipsisa32-* | mipsisa32el-* \
| mipsisa32r2-* | mipsisa32r2el-* \ | mipsisa32r2-* | mipsisa32r2el-* \
| mipsisa32r6-* | mipsisa32r6el-* \
| mipsisa64-* | mipsisa64el-* \ | mipsisa64-* | mipsisa64el-* \
| mipsisa64r2-* | mipsisa64r2el-* \ | mipsisa64r2-* | mipsisa64r2el-* \
| mipsisa64r6-* | mipsisa64r6el-* \
| mipsisa64sb1-* | mipsisa64sb1el-* \ | mipsisa64sb1-* | mipsisa64sb1el-* \
| mipsisa64sr71k-* | mipsisa64sr71kel-* \ | mipsisa64sr71k-* | mipsisa64sr71kel-* \
| mipsr5900-* | mipsr5900el-* \
| mipstx39-* | mipstx39el-* \ | mipstx39-* | mipstx39el-* \
| mmix-* \ | mmix-* \
| mt-* \ | mt-* \
| msp430-* \ | msp430-* \
| nds32-* | nds32le-* | nds32be-* \ | nios-* | nios2-* \
| nios-* | nios2-* | nios2eb-* | nios2el-* \
| none-* | np1-* | ns16k-* | ns32k-* \ | none-* | np1-* | ns16k-* | ns32k-* \
| open8-* \
| or1k*-* \
| orion-* \ | orion-* \
| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \
| pyramid-* \ | pyramid-* \
| rl78-* | romp-* | rs6000-* | rx-* \ | romp-* | rs6000-* \
| sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ | sh-* | sh[1234]-* | sh[24]a-* | sh[23]e-* | sh[34]eb-* | shbe-* \
| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
| sparclite-* \ | sparclite-* \
| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \ | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | strongarm-* | sv1-* | sx?-* \
| tahoe-* \ | tahoe-* | thumb-* \
| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
| tile*-* \
| tron-* \ | tron-* \
| ubicom32-* \ | v850-* | v850e-* | vax-* \
| v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
| vax-* \
| visium-* \
| we32k-* \ | we32k-* \
| x86-* | x86_64-* | xc16x-* | xps100-* \ | x86-* | x86_64-* | xps100-* | xscale-* | xscalee[bl]-* \
| xstormy16-* | xtensa*-* \ | xstormy16-* | xtensa-* \
| ymp-* \ | ymp-* \
| z8k-* | z80-*) | z8k-*)
;; ;;
# Recognize the basic CPU types without company name, with glob match. m32c-*)
xtensa*)
basic_machine=$basic_machine-unknown
;; ;;
# Recognize the various machine names and aliases which stand # Recognize the various machine names and aliases which stand
# for a CPU type and a company and sometimes even an OS. # for a CPU type and a company and sometimes even an OS.
@@ -468,7 +392,7 @@ case $basic_machine in
basic_machine=a29k-amd basic_machine=a29k-amd
os=-udi os=-udi
;; ;;
abacus) abacus)
basic_machine=abacus-unknown basic_machine=abacus-unknown
;; ;;
adobe68k) adobe68k)
@@ -514,13 +438,6 @@ case $basic_machine in
basic_machine=m68k-apollo basic_machine=m68k-apollo
os=-bsd os=-bsd
;; ;;
aros)
basic_machine=i386-pc
os=-aros
;;
asmjs)
basic_machine=asmjs-unknown
;;
aux) aux)
basic_machine=m68k-apple basic_machine=m68k-apple
os=-aux os=-aux
@@ -529,35 +446,10 @@ case $basic_machine in
basic_machine=ns32k-sequent basic_machine=ns32k-sequent
os=-dynix os=-dynix
;; ;;
blackfin)
basic_machine=bfin-unknown
os=-linux
;;
blackfin-*)
basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'`
os=-linux
;;
bluegene*)
basic_machine=powerpc-ibm
os=-cnk
;;
c54x-*)
basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
c55x-*)
basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
c6x-*)
basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
c90) c90)
basic_machine=c90-cray basic_machine=c90-cray
os=-unicos os=-unicos
;; ;;
cegcc)
basic_machine=arm-unknown
os=-cegcc
;;
convex-c1) convex-c1)
basic_machine=c1-convex basic_machine=c1-convex
os=-bsd os=-bsd
@@ -586,8 +478,8 @@ case $basic_machine in
basic_machine=craynv-cray basic_machine=craynv-cray
os=-unicosmp os=-unicosmp
;; ;;
cr16 | cr16-*) cr16c)
basic_machine=cr16-unknown basic_machine=cr16c-unknown
os=-elf os=-elf
;; ;;
crds | unos) crds | unos)
@@ -625,10 +517,6 @@ case $basic_machine in
basic_machine=m88k-motorola basic_machine=m88k-motorola
os=-sysv3 os=-sysv3
;; ;;
dicos)
basic_machine=i686-pc
os=-dicos
;;
djgpp) djgpp)
basic_machine=i586-pc basic_machine=i586-pc
os=-msdosdjgpp os=-msdosdjgpp
@@ -744,6 +632,7 @@ case $basic_machine in
i370-ibm* | ibm*) i370-ibm* | ibm*)
basic_machine=i370-ibm basic_machine=i370-ibm
;; ;;
# I'm not sure what "Sysv32" means. Should this be sysv3.2?
i*86v32) i*86v32)
basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
os=-sysv32 os=-sysv32
@@ -782,17 +671,6 @@ case $basic_machine in
basic_machine=m68k-isi basic_machine=m68k-isi
os=-sysv os=-sysv
;; ;;
leon-*|leon[3-9]-*)
basic_machine=sparc-`echo $basic_machine | sed 's/-.*//'`
;;
m68knommu)
basic_machine=m68k-unknown
os=-linux
;;
m68knommu-*)
basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'`
os=-linux
;;
m88k-omron*) m88k-omron*)
basic_machine=m88k-omron basic_machine=m88k-omron
;; ;;
@@ -804,21 +682,10 @@ case $basic_machine in
basic_machine=ns32k-utek basic_machine=ns32k-utek
os=-sysv os=-sysv
;; ;;
microblaze*)
basic_machine=microblaze-xilinx
;;
mingw64)
basic_machine=x86_64-pc
os=-mingw64
;;
mingw32) mingw32)
basic_machine=i686-pc basic_machine=i386-pc
os=-mingw32 os=-mingw32
;; ;;
mingw32ce)
basic_machine=arm-unknown
os=-mingw32ce
;;
miniframe) miniframe)
basic_machine=m68000-convergent basic_machine=m68000-convergent
;; ;;
@@ -840,10 +707,6 @@ case $basic_machine in
basic_machine=powerpc-unknown basic_machine=powerpc-unknown
os=-morphos os=-morphos
;; ;;
moxiebox)
basic_machine=moxie-unknown
os=-moxiebox
;;
msdos) msdos)
basic_machine=i386-pc basic_machine=i386-pc
os=-msdos os=-msdos
@@ -851,18 +714,10 @@ case $basic_machine in
ms1-*) ms1-*)
basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
;; ;;
msys)
basic_machine=i686-pc
os=-msys
;;
mvs) mvs)
basic_machine=i370-ibm basic_machine=i370-ibm
os=-mvs os=-mvs
;; ;;
nacl)
basic_machine=le32-unknown
os=-nacl
;;
ncr3000) ncr3000)
basic_machine=i486-ncr basic_machine=i486-ncr
os=-sysv4 os=-sysv4
@@ -927,12 +782,6 @@ case $basic_machine in
np1) np1)
basic_machine=np1-gould basic_machine=np1-gould
;; ;;
neo-tandem)
basic_machine=neo-tandem
;;
nse-tandem)
basic_machine=nse-tandem
;;
nsr-tandem) nsr-tandem)
basic_machine=nsr-tandem basic_machine=nsr-tandem
;; ;;
@@ -963,14 +812,6 @@ case $basic_machine in
basic_machine=i860-intel basic_machine=i860-intel
os=-osf os=-osf
;; ;;
parisc)
basic_machine=hppa-unknown
os=-linux
;;
parisc-*)
basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'`
os=-linux
;;
pbd) pbd)
basic_machine=sparc-tti basic_machine=sparc-tti
;; ;;
@@ -1015,10 +856,9 @@ case $basic_machine in
;; ;;
power) basic_machine=power-ibm power) basic_machine=power-ibm
;; ;;
ppc | ppcbe) basic_machine=powerpc-unknown ppc) basic_machine=powerpc-unknown
;; ;;
ppc-* | ppcbe-*) ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
;; ;;
ppcle | powerpclittle | ppc-le | powerpc-little) ppcle | powerpclittle | ppc-le | powerpc-little)
basic_machine=powerpcle-unknown basic_machine=powerpcle-unknown
@@ -1043,11 +883,7 @@ case $basic_machine in
basic_machine=i586-unknown basic_machine=i586-unknown
os=-pw32 os=-pw32
;; ;;
rdos | rdos64) rdos)
basic_machine=x86_64-pc
os=-rdos
;;
rdos32)
basic_machine=i386-pc basic_machine=i386-pc
os=-rdos os=-rdos
;; ;;
@@ -1077,10 +913,6 @@ case $basic_machine in
sb1el) sb1el)
basic_machine=mipsisa64sb1el-unknown basic_machine=mipsisa64sb1el-unknown
;; ;;
sde)
basic_machine=mipsisa32-sde
os=-elf
;;
sei) sei)
basic_machine=mips-sei basic_machine=mips-sei
os=-seiux os=-seiux
@@ -1092,9 +924,6 @@ case $basic_machine in
basic_machine=sh-hitachi basic_machine=sh-hitachi
os=-hms os=-hms
;; ;;
sh5el)
basic_machine=sh5le-unknown
;;
sh64) sh64)
basic_machine=sh64-unknown basic_machine=sh64-unknown
;; ;;
@@ -1116,9 +945,6 @@ case $basic_machine in
basic_machine=i860-stratus basic_machine=i860-stratus
os=-sysv4 os=-sysv4
;; ;;
strongarm-* | thumb-*)
basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
sun2) sun2)
basic_machine=m68000-sun basic_machine=m68000-sun
;; ;;
@@ -1175,9 +1001,17 @@ case $basic_machine in
basic_machine=t90-cray basic_machine=t90-cray
os=-unicos os=-unicos
;; ;;
tile*) tic54x | c54x*)
basic_machine=$basic_machine-unknown basic_machine=tic54x-unknown
os=-linux-gnu os=-coff
;;
tic55x | c55x*)
basic_machine=tic55x-unknown
os=-coff
;;
tic6x | c6x*)
basic_machine=tic6x-unknown
os=-coff
;; ;;
tx39) tx39)
basic_machine=mipstx39-unknown basic_machine=mipstx39-unknown
@@ -1246,9 +1080,6 @@ case $basic_machine in
xps | xps100) xps | xps100)
basic_machine=xps100-honeywell basic_machine=xps100-honeywell
;; ;;
xscale-* | xscalee[bl]-*)
basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'`
;;
ymp) ymp)
basic_machine=ymp-cray basic_machine=ymp-cray
os=-unicos os=-unicos
@@ -1257,10 +1088,6 @@ case $basic_machine in
basic_machine=z8k-unknown basic_machine=z8k-unknown
os=-sim os=-sim
;; ;;
z80-*-coff)
basic_machine=z80-unknown
os=-sim
;;
none) none)
basic_machine=none-none basic_machine=none-none
os=-none os=-none
@@ -1299,7 +1126,7 @@ case $basic_machine in
we32k) we32k)
basic_machine=we32k-att basic_machine=we32k-att
;; ;;
sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele) sh[1234] | sh[24]a | sh[34]eb | sh[1234]le | sh[23]ele)
basic_machine=sh-unknown basic_machine=sh-unknown
;; ;;
sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
@@ -1346,12 +1173,9 @@ esac
if [ x"$os" != x"" ] if [ x"$os" != x"" ]
then then
case $os in case $os in
# First match some system type aliases # First match some system type aliases
# that might get confused with valid system types. # that might get confused with valid system types.
# -solaris* is a basic system type, with this one exception. # -solaris* is a basic system type, with this one exception.
-auroraux)
os=-auroraux
;;
-solaris1 | -solaris1.*) -solaris1 | -solaris1.*)
os=`echo $os | sed -e 's|solaris1|sunos4|'` os=`echo $os | sed -e 's|solaris1|sunos4|'`
;; ;;
@@ -1372,31 +1196,29 @@ case $os in
# Each alternative MUST END IN A *, to match a version number. # Each alternative MUST END IN A *, to match a version number.
# -sysv* is not here because it comes later, after sysvr4. # -sysv* is not here because it comes later, after sysvr4.
-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
| -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\ | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\
| -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \ | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \
| -sym* | -kopensolaris* | -plan9* \
| -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
| -aos* | -aros* | -cloudabi* \ | -aos* \
| -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
| -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
| -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
| -bitrig* | -openbsd* | -solidbsd* \ | -openbsd* | -solidbsd* \
| -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
| -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
| -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
| -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
| -chorusos* | -chorusrdb* | -cegcc* \ | -chorusos* | -chorusrdb* \
| -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
| -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \ | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \
| -linux-newlib* | -linux-musl* | -linux-uclibc* \ | -uxpv* | -beos* | -mpeix* | -udk* \
| -uxpv* | -beos* | -mpeix* | -udk* | -moxiebox* \
| -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
| -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
| -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
| -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
| -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
| -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
| -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* | -tirtos*) | -skyos* | -haiku* | -rdos*)
# Remember, each alternative MUST END IN *, to match a version number. # Remember, each alternative MUST END IN *, to match a version number.
;; ;;
-qnx*) -qnx*)
@@ -1435,7 +1257,7 @@ case $os in
-opened*) -opened*)
os=-openedition os=-openedition
;; ;;
-os400*) -os400*)
os=-os400 os=-os400
;; ;;
-wince*) -wince*)
@@ -1484,7 +1306,7 @@ case $os in
-sinix*) -sinix*)
os=-sysv4 os=-sysv4
;; ;;
-tpf*) -tpf*)
os=-tpf os=-tpf
;; ;;
-triton*) -triton*)
@@ -1520,14 +1342,12 @@ case $os in
-aros*) -aros*)
os=-aros os=-aros
;; ;;
-kaos*)
os=-kaos
;;
-zvmoe) -zvmoe)
os=-zvmoe os=-zvmoe
;; ;;
-dicos*)
os=-dicos
;;
-nacl*)
;;
-none) -none)
;; ;;
*) *)
@@ -1550,12 +1370,6 @@ else
# system, and we'll never get to this point. # system, and we'll never get to this point.
case $basic_machine in case $basic_machine in
score-*)
os=-elf
;;
spu-*)
os=-elf
;;
*-acorn) *-acorn)
os=-riscix1.2 os=-riscix1.2
;; ;;
@@ -1565,24 +1379,9 @@ case $basic_machine in
arm*-semi) arm*-semi)
os=-aout os=-aout
;; ;;
c4x-* | tic4x-*) c4x-* | tic4x-*)
os=-coff os=-coff
;; ;;
c8051-*)
os=-elf
;;
hexagon-*)
os=-elf
;;
tic54x-*)
os=-coff
;;
tic55x-*)
os=-coff
;;
tic6x-*)
os=-coff
;;
# This must come before the *-dec entry. # This must come before the *-dec entry.
pdp10-*) pdp10-*)
os=-tops20 os=-tops20
@@ -1601,13 +1400,13 @@ case $basic_machine in
;; ;;
m68000-sun) m68000-sun)
os=-sunos3 os=-sunos3
# This also exists in the configure program, but was not the
# default.
# os=-sunos4
;; ;;
m68*-cisco) m68*-cisco)
os=-aout os=-aout
;; ;;
mep-*)
os=-elf
;;
mips*-cisco) mips*-cisco)
os=-elf os=-elf
;; ;;
@@ -1632,7 +1431,7 @@ case $basic_machine in
*-ibm) *-ibm)
os=-aix os=-aix
;; ;;
*-knuth) *-knuth)
os=-mmixware os=-mmixware
;; ;;
*-wec) *-wec)
@@ -1737,7 +1536,7 @@ case $basic_machine in
-sunos*) -sunos*)
vendor=sun vendor=sun
;; ;;
-cnk*|-aix*) -aix*)
vendor=ibm vendor=ibm
;; ;;
-beos*) -beos*)

View File

@@ -1,3 +1,4 @@
# #
# This file is the main build configuration file for fish. It is used # This file is the main build configuration file for fish. It is used
# to determine your systems capabilities, and tries to adapt fish to # to determine your systems capabilities, and tries to adapt fish to
@@ -8,22 +9,25 @@
# configure the build process. # configure the build process.
# #
m4_syscmd([build_tools/git_version_gen.sh 2>/dev/null]) AC_INIT(fish,2.0.0,fish-users@lists.sf.net)
AC_PREREQ([2.60]) conf_arg=$@
AC_INIT(fish,
m4_esyscmd([cut -f 3 -d ' ' FISH-BUILD-VERSION-FILE | tr -d '\n']),
fish-users@lists.sourceforge.net)
# #
# List of output variables produced by this configure script # List of output variables produced by this configure script
# #
AC_SUBST(docdir)
AC_SUBST(HAVE_GETTEXT) AC_SUBST(HAVE_GETTEXT)
AC_SUBST(HAVE_DOXYGEN)
AC_SUBST(LDFLAGS_FISH) AC_SUBST(LDFLAGS_FISH)
AC_SUBST(WCHAR_T_BITS) AC_SUBST(LIBS_FISH)
AC_SUBST(EXTRA_PCRE2) AC_SUBST(LIBS_FISH_INDENT)
AC_SUBST(LIBS_FISH_PAGER)
AC_SUBST(LIBS_FISHD)
AC_SUBST(LIBS_MIMEDB)
AC_SUBST(localedir)
AC_SUBST(optbindirs)
AC_SUBST(prefix)
# #
@@ -89,13 +93,51 @@ fi
# #
AC_PROG_CXX([g++ c++]) AC_PROG_CXX([g++ c++])
AC_PROG_CPP
AC_PROG_INSTALL AC_PROG_INSTALL
AC_PROG_SED
AC_LANG(C++)
AC_USE_SYSTEM_EXTENSIONS
echo "CXXFLAGS: $CXXFLAGS" echo "CXXFLAGS: $CXXFLAGS"
#
# Detect directories which may contain additional headers, libraries
# and commands. This needs to be done early - before Autoconf starts
# to mess with CFLAGS and all the other environemnt variables.
#
# This mostly helps OS X users, since fink usually installs out of
# tree and doesn't update CFLAGS.
#
# It also helps FreeBSD which puts libiconv in /usr/local/lib
for i in /usr/pkg /sw /opt /opt/local /usr/local; do
AC_MSG_CHECKING([for $i/include include directory])
if test -d $i/include; then
AC_MSG_RESULT(yes)
CXXFLAGS="$CXXFLAGS -I$i/include/"
CFLAGS="$CFLAGS -I$i/include/"
else
AC_MSG_RESULT(no)
fi
AC_MSG_CHECKING([for $i/lib library directory])
if test -d $i/lib; then
AC_MSG_RESULT(yes)
LDFLAGS="$LDFLAGS -L$i/lib/ -Wl,-rpath,$i/lib/"
else
AC_MSG_RESULT(no)
fi
AC_MSG_CHECKING([for $i/bin command directory])
if test -d $i/bin; then
AC_MSG_RESULT(yes)
optbindirs="$optbindirs $i/bin"
else
AC_MSG_RESULT(no)
fi
done
# #
# Tell autoconf to create config.h header # Tell autoconf to create config.h header
# #
@@ -108,19 +150,11 @@ AC_CONFIG_HEADERS(config.h)
# #
AH_BOTTOM([#if __GNUC__ >= 3 AH_BOTTOM([#if __GNUC__ >= 3
#ifndef __warn_unused
#define __warn_unused __attribute__ ((warn_unused_result)) #define __warn_unused __attribute__ ((warn_unused_result))
#endif
#ifndef __sentinel
#define __sentinel __attribute__ ((sentinel)) #define __sentinel __attribute__ ((sentinel))
#endif
#ifndef __packed
#define __packed __attribute__ ((packed))
#endif
#else #else
#define __warn_unused #define __warn_unused
#define __sentinel #define __sentinel
#define __packed
#endif]) #endif])
@@ -150,48 +184,6 @@ AS_IF([test x$local_gettext != xno],
], ],
) )
#
# Build/clean the documentation only if Doxygen is available
#
doxygen_minimum=1.8.7
AC_ARG_WITH(
doxygen,
AS_HELP_STRING(
[--with-doxygen],
[use Doxygen to regenerate documentation]
),
[use_doxygen=$withval],
[use_doxygen=auto]
)
AS_IF([test "$use_doxygen" != "no"],
[
AC_CHECK_PROGS([found_doxygen], [doxygen], [no])
if test "$found_doxygen" != no; then
# test version
AC_MSG_CHECKING([the doxygen version])
doxygen_version=`doxygen --version 2>/dev/null`
AC_MSG_RESULT([$doxygen_version])
dnl This requires autoconf 2.60 or newer
AS_VERSION_COMPARE([$doxygen_version], [$doxygen_minimum],
[ if test "$use_doxygen" = auto; then
AC_MSG_WARN([doxygen version $doxygen_version found, but $doxygen_minimum required])
HAVE_DOXYGEN=0
else
AC_MSG_FAILURE([doxygen version $doxygen_version found, but $doxygen_minimum required])
fi
],
[HAVE_DOXYGEN=1], [HAVE_DOXYGEN=1])
elif test "$use_doxygen" != auto; then
AC_MSG_FAILURE([--with-doxygen was given, but the doxygen program could not be found])
else
HAVE_DOXYGEN=0
fi
],
)
# #
# Try to enable large file support. This will make sure that on systems # Try to enable large file support. This will make sure that on systems
# where off_t can be either 32 or 64 bit, the latter size is used. On # where off_t can be either 32 or 64 bit, the latter size is used. On
@@ -200,35 +192,57 @@ AS_IF([test "$use_doxygen" != "no"],
CXXFLAGS="$CXXFLAGS -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64" CXXFLAGS="$CXXFLAGS -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64"
# fish does not use exceptions
# Disabling exceptions saves about 20% (!) of the compiled code size
CXXFLAGS="$CXXFLAGS -fno-exceptions"
# #
# -Wall is there to keep me on my toes # If we are using gcc, set some flags that increase the odds of the
# But signed comparison warnings are way too aggressive # compiler producing a working binary...
# #
CXXFLAGS="$CXXFLAGS -Wall -Wno-sign-compare" if test "$GCC" = yes; then
# #
# This is needed in order to get the really cool backtraces on Linux # -fno-optimize-sibling-calls seems to work around a bug where
# # sending a SIGWINCH to fish on NetBSD 3.0 causes fish to exit when
# compiled with GCC 3.3.3. This is probably either a compiler bug
# or a libc bug, but adding this flag seems to fix things for
# now. Long term, the real problem should be tracked down and
# truly fixed, at which point we can remove this silly flag. This
# bug has been verified to not exist on Linux using GCC 3.3.3.
#
AC_MSG_CHECKING([for -rdynamic linker flag]) GCC_VERSION=$($CC -dumpversion)
prev_LDFLAGS="$LDFLAGS" GCC_VERSION_MAJOR=$(echo $GCC_VERSION | cut -d'.' -f1)
LDFLAGS="$LDFLAGS -rdynamic" GCC_VERSION_MINOR=$(echo $GCC_VERSION | cut -d'.' -f2)
AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])], GCC_VERSION_PATCH=$(echo $GCC_VERSION | cut -d'.' -f3)
[
AC_MSG_RESULT([yes]) if test "$GCC_VERSION_MAJOR" -le 3; then
LDFLAGS_FISH="$LDFLAGS_FISH -rdynamic" if test 0"$GCC_VERSION_MINOR" -le 3; then
], [ if test 0"$GCC_VERSION_PATCH" -le 3; then
AC_MSG_RESULT([no]) CXXFLAGS="$CXXFLAGS -fno-optimize-sibling-calls"
LDFLAGS_FISH="$LDFLAGS_FISH" fi
]) fi
LDFLAGS="$prev_LDFLAGS" fi
# fish does not use exceptions
# Disabling exceptions saves about 20% (!) of the compiled code size
CXXFLAGS="$CXXFLAGS -fno-exceptions"
#
# -Wall is there to keep me on my toes
#
# Some day...
CXXFLAGS="$CXXFLAGS -Wall"
#
# This is needed in order to get the really cool backtraces on Linux
#
if test `uname` != "Darwin"; then
LDFLAGS_FISH="$LDFLAGS_FISH -rdynamic"
fi
fi
# #
@@ -268,7 +282,7 @@ if test "$glibc" = yes; then
# fallback.h, in order to keep fish working on non-gnu platforms. # fallback.h, in order to keep fish working on non-gnu platforms.
# #
CXXFLAGS="$CXXFLAGS -D_GNU_SOURCE=1 -D_ISO99_SOURCE=1" CFLAGS="$CFLAGS -D_GNU_SOURCE=1 -D_ISO99_SOURCE=1"
else else
AC_MSG_RESULT(no) AC_MSG_RESULT(no)
fi fi
@@ -307,6 +321,35 @@ case $target_os in
;; ;;
esac esac
# Check for Solaris curses tputs having fixed length parameter list.
AC_MSG_CHECKING([if we are using non varargs tparm.])
AC_COMPILE_IFELSE(
[
AC_LANG_PROGRAM(
[
#include <curses.h>
#include <term.h>
],
[
tparm( "" );
]
)
],
[tparm_solaris_kludge=no],
[tparm_solaris_kludge=yes]
)
if test "x$tparm_solaris_kludge" = "xyes"; then
AC_MSG_RESULT(yes)
AC_DEFINE(
[TPARM_SOLARIS_KLUDGE],
[1],
[Define to 1 if tparm accepts a fixed amount of paramters.]
)
else
AC_MSG_RESULT(no)
fi
# #
# BSD-specific flags go here # BSD-specific flags go here
# #
@@ -324,6 +367,40 @@ case $target_os in
esac esac
#
# Set up PREFIX and related preprocessor symbols. Fish needs to know
# where it will be installed. One of the reasons for this is so that
# it can make sure the fish installation directory is in the path
# during startup.
#
if [[ "$prefix" = NONE ]]; then
prefix=/usr/local
fi
#
# Set up the directory where the documentation files should be
# installed
#
AC_ARG_VAR( [docdir], [Documentation direcotry] )
if test -z $docdir; then
docdir=$datadir/doc/fish
else
docdir=$docdir
fi
#
# Set up locale directory. This is where the .po files will be
# installed.
#
localedir=$datadir/locale
# #
# See if Linux procfs is present. This is used to get extra # See if Linux procfs is present. This is used to get extra
# information about running processes. # information about running processes.
@@ -343,9 +420,6 @@ AC_DEFINE(
[Define to 1 if the wgettext function should be used for translating strings.] [Define to 1 if the wgettext function should be used for translating strings.]
) )
# Disable curses macros that conflict with the STL
AC_DEFINE([NCURSES_NOMACROS], [1], [Define to 1 to disable ncurses macros that conflict with the STL])
AC_DEFINE([NOMACROS], [1], [Define to 1 to disable curses macros that conflict with the STL])
# #
# Check presense of various libraries. This is done on a per-binary # Check presense of various libraries. This is done on a per-binary
@@ -355,37 +429,105 @@ AC_DEFINE([NOMACROS], [1], [Define to 1 to disable curses macros that conflict w
# #
# Check for os dependant libraries for all binaries. # Check for os dependant libraries for all binaries.
LIBS_COMMON=$LIBS
LIBS=""
AC_SEARCH_LIBS( connect, socket, , [AC_MSG_ERROR([Cannot find the socket library, needed to build this package.] )] ) AC_SEARCH_LIBS( connect, socket, , [AC_MSG_ERROR([Cannot find the socket library, needed to build this package.] )] )
AC_SEARCH_LIBS( nanosleep, rt, , [AC_MSG_ERROR([Cannot find the rt library, needed to build this package.] )] ) AC_SEARCH_LIBS( nanosleep, rt, , [AC_MSG_ERROR([Cannot find the rt library, needed to build this package.] )] )
AC_SEARCH_LIBS( shm_open, rt, , [AC_MSG_ERROR([Cannot find the rt library, needed to build this package.] )] )
AC_SEARCH_LIBS( pthread_create, pthread, , [AC_MSG_ERROR([Cannot find the pthread library, needed to build this package.] )] ) AC_SEARCH_LIBS( pthread_create, pthread, , [AC_MSG_ERROR([Cannot find the pthread library, needed to build this package.] )] )
AC_SEARCH_LIBS( setupterm, [ncurses tinfo curses], , [AC_MSG_ERROR([Could not find a curses implementation, needed to build fish. If this is Linux, try running 'sudo apt-get install libncurses5-dev' or 'sudo yum install ncurses-devel'])] ) AC_SEARCH_LIBS( setupterm, [ncurses curses], , [AC_MSG_ERROR([Could not find a curses implementation, needed to build fish])] )
AC_SEARCH_LIBS( [nan], [m], [AC_DEFINE( [HAVE_NAN], [1], [Define to 1 if you have the nan function])] ) AC_SEARCH_LIBS( [nan], [m], [AC_DEFINE( [HAVE_NAN], [1], [Define to 1 if you have the nan function])] )
AC_SEARCH_LIBS( [backtrace_symbols_fd], [execinfo] ) LIBS_SHARED=$LIBS
LIBS=$LIBS_COMMON
#
# Check for libraries needed by fish.
#
LIBS_COMMON=$LIBS
LIBS="$LIBS_SHARED"
if test x$local_gettext != xno; then if test x$local_gettext != xno; then
AC_SEARCH_LIBS( gettext, intl,,) AC_SEARCH_LIBS( gettext, intl,,)
fi fi
# Check for libiconv_open if we can't find iconv_open. Silly OS X does
# weird macro magic for the sole purpose of amusing me.
AC_SEARCH_LIBS( iconv_open, iconv, , [AC_SEARCH_LIBS( libiconv_open, iconv, , [AC_MSG_ERROR([Could not find an iconv implementation, needed to build fish])] )] )
LIBS_FISH=$LIBS
LIBS=$LIBS_COMMON
#
# Check for libraries needed by fish_indent.
#
LIBS_COMMON=$LIBS
LIBS="$LIBS_SHARED"
if test x$local_gettext != xno; then
AC_SEARCH_LIBS( gettext, intl,,)
fi
LIBS_FISH_INDENT=$LIBS
LIBS=$LIBS_COMMON
#
# Check for libraries needed by fish_pager.
#
LIBS_COMMON=$LIBS
LIBS="$LIBS_SHARED"
if test x$local_gettext != xno; then
AC_SEARCH_LIBS( gettext, intl,,)
fi
AC_SEARCH_LIBS( iconv_open, iconv, , [AC_SEARCH_LIBS( libiconv_open, iconv, , [AC_MSG_ERROR([Could not find an iconv implementation, needed to build fish])] )] )
LIBS_FISH_PAGER=$LIBS
LIBS=$LIBS_COMMON
#
# Check for libraries needed by fishd.
#
LIBS_COMMON=$LIBS
LIBS="$LIBS_SHARED"
if test x$local_gettext != xno; then
AC_SEARCH_LIBS( gettext, intl,,)
fi
AC_SEARCH_LIBS( iconv_open, iconv, , [AC_SEARCH_LIBS( libiconv_open, iconv, , [AC_MSG_ERROR([Could not find an iconv implementation, needed to build fish])] )] )
LIBS_FISHD=$LIBS
LIBS=$LIBS_COMMON
#
# Check for libraries needed by mimedb.
#
LIBS_COMMON=$LIBS
LIBS="$LIBS_SHARED"
if test x$local_gettext != xno; then
AC_SEARCH_LIBS( gettext, intl,,)
fi
LIBS_MIMEDB=$LIBS
LIBS=$LIBS_COMMON
# #
# Check presense of various header files # Check presense of various header files
# #
AC_CHECK_HEADERS([getopt.h termios.h sys/resource.h term.h ncurses/term.h ncurses.h ncurses/curses.h curses.h stropts.h siginfo.h sys/select.h sys/ioctl.h execinfo.h spawn.h sys/sysctl.h]) AC_CHECK_HEADERS([getopt.h termios.h sys/resource.h term.h ncurses/term.h ncurses.h curses.h stropts.h siginfo.h sys/select.h sys/ioctl.h execinfo.h spawn.h])
if test x$local_gettext != xno; then if test x$local_gettext != xno; then
AC_CHECK_HEADERS([libintl.h]) AC_CHECK_HEADERS([libintl.h])
fi fi
AC_CHECK_HEADER(
# [regex.h],
# Get the size in bits of wchar_t, needed for configuring the pcre2 build [
# and for code that #includes pcre2.h AC_DEFINE(
# [HAVE_REGEX_H],
[1],
AC_CHECK_SIZEOF(wchar_t) [Define to 1 if you have the <regex.h> header file.]
WCHAR_T_BITS=`expr 8 \* $ac_cv_sizeof_wchar_t` )
AC_DEFINE_UNQUOTED([WCHAR_T_BITS], [$WCHAR_T_BITS], [The size of wchar_t in bits.]) ],
[AC_MSG_ERROR([Could not find the header regex.h, needed to build fish])]
)
# #
@@ -417,7 +559,7 @@ AC_DEFINE_UNQUOTED([WCHAR_T_BITS], [$WCHAR_T_BITS], [The size of wchar_t in bits
# conditional definition of __EXTENSIONS__, to avoid redundant tests. # conditional definition of __EXTENSIONS__, to avoid redundant tests.
# #
XCXXFLAGS="$CXXFLAGS" XCFLAGS="$CXXFLAGS"
echo checking how to use -D_XOPEN_SOURCE=600 and -D_POSIX_C_SOURCE=200112L... echo checking how to use -D_XOPEN_SOURCE=600 and -D_POSIX_C_SOURCE=200112L...
local_found_posix_switch=no local_found_posix_switch=no
@@ -425,7 +567,7 @@ local_found_posix_switch=no
for i in "" "-D_POSIX_C_SOURCE=200112L" "-D_XOPEN_SOURCE=600 -D_POSIX_C_SOURCE=200112L"; do for i in "" "-D_POSIX_C_SOURCE=200112L" "-D_XOPEN_SOURCE=600 -D_POSIX_C_SOURCE=200112L"; do
AC_MSG_CHECKING( if switches \"$i\" works) AC_MSG_CHECKING( if switches \"$i\" works)
CXXFLAGS="$XCXXFLAGS $i" CFLAGS="$XCFLAGS $i"
# #
# Try to run this program, which should test various extensions # Try to run this program, which should test various extensions
@@ -456,10 +598,6 @@ for i in "" "-D_POSIX_C_SOURCE=200112L" "-D_XOPEN_SOURCE=600 -D_POSIX_C_SOURCE=2
/* As above (under at least Linux and FreeBSD). */ /* As above (under at least Linux and FreeBSD). */
#include <sys/ioctl.h> #include <sys/ioctl.h>
#endif #endif
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif
], ],
[ [
/* Avert high-level optimisation, by making the program's /* Avert high-level optimisation, by making the program's
@@ -503,19 +641,9 @@ done
# #
if test ! x$local_found_posix_switch = xyes; then if test ! x$local_found_posix_switch = xyes; then
CXXFLAGS="$XCXXFLAGS" CFLAGS="$XCFLAGS"
fi fi
#
# Detect nanoseconds fields in struct stat
#
AC_CHECK_MEMBERS([struct stat.st_mtimespec.tv_nsec])
AC_CHECK_MEMBERS([struct stat.st_mtim.tv_nsec])
#
# Check for D_TYPE in dirent, only on BSD and Linux
#
AC_STRUCT_DIRENT_D_TYPE
# #
# Check for presense of various functions used by fish # Check for presense of various functions used by fish
@@ -524,10 +652,7 @@ AC_STRUCT_DIRENT_D_TYPE
AC_CHECK_FUNCS( wcsdup wcsndup wcslen wcscasecmp wcsncasecmp fwprintf ) AC_CHECK_FUNCS( wcsdup wcsndup wcslen wcscasecmp wcsncasecmp fwprintf )
AC_CHECK_FUNCS( futimes wcwidth wcswidth wcstok fputwc fgetwc ) AC_CHECK_FUNCS( futimes wcwidth wcswidth wcstok fputwc fgetwc )
AC_CHECK_FUNCS( wcstol wcslcat wcslcpy lrand48_r killpg ) AC_CHECK_FUNCS( wcstol wcslcat wcslcpy lrand48_r killpg )
AC_CHECK_FUNCS( backtrace backtrace_symbols_fd sysconf getifaddrs ) AC_CHECK_FUNCS( backtrace backtrace_symbols sysconf getifaddrs )
AC_CHECK_FUNCS( futimens clock_gettime )
AC_CHECK_DECL( [mkostemp], [ AC_CHECK_FUNCS([mkostemp]) ] )
if test x$local_gettext != xno; then if test x$local_gettext != xno; then
AC_CHECK_FUNCS( gettext dcgettext ) AC_CHECK_FUNCS( gettext dcgettext )
@@ -618,7 +743,7 @@ AC_LINK_IFELSE(
# #
# If we have a fwprintf in libc, test that it actually works. As of # If we have a fwprintf in libc, test that it actually works. As of
# March 2006, it is broken under DragonFly BSD. # March 2006, it is broken under Dragonfly BSD.
# #
if test "$ac_cv_func_fwprintf" = yes; then if test "$ac_cv_func_fwprintf" = yes; then
@@ -703,213 +828,62 @@ else
AC_MSG_RESULT(no) AC_MSG_RESULT(no)
fi fi
# Check for sys_errlist # Check if getopt_long exists and works
AC_MSG_CHECKING([for sys_errlist array]) AC_MSG_CHECKING([if getopt_long exists and works])
AC_TRY_LINK( AC_TRY_LINK(
[ [
#include <stdio.h> #if HAVE_GETOPT_H
#include <getopt.h>
#endif
], ],
[ [
const char *p; static struct option
p = sys_errlist[sys_nerr]; long_options[] =
{
0, 0, 0, 0
}
;
int opt = getopt_long( 0,
0,
0,
long_options,
0 );
], ],
have_sys_errlist=yes, have_working_getopt_long=yes,
have_sys_errlist=no have_working_getopt_long=no
) )
if test "$have_sys_errlist" = yes; then if test "$have_working_getopt_long" = yes; then
AC_MSG_RESULT(yes) AC_MSG_RESULT(yes)
AC_DEFINE( AC_DEFINE(
[HAVE_SYS_ERRLIST], [HAVE_WORKING_GETOPT_LONG],
[1], [1],
[Define to 1 if the sys_errlist array is available.] [Define to 1 if getopt_long exists and works.]
) )
else else
AC_MSG_RESULT(no) AC_MSG_RESULT(no)
fi fi
# Check for _sys_errs # Check if del_curterm is broken - in that case we redefine
AC_MSG_CHECKING([for _sys_errs array]) # del_curterm as a no-op, to avoid a double-free
AC_TRY_LINK(
[
#include <string>
],
[
std::string p;
extern const char _sys_errs[];
extern const int _sys_index[];
p = _sys_errs[_sys_index[0]];
],
have__sys__errs=yes,
have__sys__errs=no
)
if test "$have__sys__errs" = yes; then
AC_MSG_RESULT(yes)
AC_DEFINE(
[HAVE__SYS__ERRS],
[1],
[Define to 1 if the _sys_errs array is available.]
)
else
AC_MSG_RESULT(no)
fi
# Check for Solaris curses tputs having fixed length parameter list. AC_MSG_CHECKING([If del_curterm is broken])
AC_MSG_CHECKING([if we are using non varargs tparm.]) case $target_os in
AC_COMPILE_IFELSE( *bsd*)
[ AC_MSG_RESULT(yes)
AC_LANG_PROGRAM( AC_DEFINE(
[ [HAVE_BROKEN_DEL_CURTERM],
#if HAVE_NCURSES_H [1],
#include <ncurses.h> [del_curterm is broken, redefine it to a no-op to avoid a double-free bug]
#elif HAVE_NCURSES_CURSES_H
#include <ncurses/curses.h>
#else
#include <curses.h>
#endif
#if HAVE_TERM_H
#include <term.h>
#elif HAVE_NCURSES_TERM_H
#include <ncurses/term.h>
#endif
],
[
tparm( "" );
]
) )
], ;;
[tparm_solaris_kludge=no], *)
[tparm_solaris_kludge=yes] AC_MSG_RESULT(no)
) ;;
if test "x$tparm_solaris_kludge" = "xyes"; then esac
AC_MSG_RESULT(yes)
AC_DEFINE(
[TPARM_SOLARIS_KLUDGE],
[1],
[Define to 1 if tparm accepts a fixed amount of paramters.]
)
else
AC_MSG_RESULT(no)
fi
pcre2_min_version=10.21 # Tell the world what we know
EXTRA_PCRE2= AC_CONFIG_FILES([Makefile fish.spec])
AC_ARG_WITH(
included-pcre2,
AS_HELP_STRING(
[--without-included-pcre2],
[build against the system PCRE2 library instead of the bundled version]
),
[included_pcre2=$withval],
[included_pcre2=auto]
)
if test "x$included_pcre2" != "xyes"; then
# test for pcre2-config
# can use either pcre2-config or pkgconfig here but only implement the former for now
AC_CHECK_PROG(PCRE2_CONFIG, pcre2-config, pcre2-config)
if test "x$PCRE2_CONFIG" != "x"; then
dnl AC_MSG_CHECKING([for $WCHAR_T_BITS-bit PCRE2])
XLIBS="$LIBS"
LIBS="$LIBS "`$PCRE2_CONFIG --libs$WCHAR_T_BITS 2>/dev/null`
XCXXFLAGS="$CXXFLAGS"
CXXFLAGS="$CXXFLAGS"`$PCRE2_CONFIG --cflags`
# cheat a bit here. the exact library is determined by $WCHAR_T_BITS,
# and so AC_CHECK_LIB won't work (can't use a variable as library name)
# AC_SEARCH_LIBS will use the existing $LIBS flags with no additional library first
AC_SEARCH_LIBS([pcre2_compile_$WCHAR_T_BITS], [],
[ # pcre2 lib found, check for minimum version
pcre2_version=`$PCRE2_CONFIG --version`
AS_VERSION_COMPARE([$pcre2_version], [$pcre2_min_version],
[ # version < minimum
AC_MSG_NOTICE([system PCRE2 library version $pcre2_version, need $pcre2_min_version or later])
if test "x$included_pcre2" = "xno"; then
# complain about pcre2 version
AC_MSG_ERROR([system PCRE2 library is too old, but --without-included-pcre2 was given.])
else
# use the internal version; undo changes to LIBS/CXXFLAGS
included_pcre2=yes
LIBS="$XLIBS"
CXXFLAGS="$XCXXFLAGS"
fi
],
[ # version == minimum
working_pcre2=yes
],
[ # version > minimum
working_pcre2=yes
]
)
],
[ # fail case; undo the changes to LIBS/CXXFLAGS
working_pcre2=no
LIBS="$XLIBS"
CXXFLAGS="$XCXXFLAGS"
]
)
fi
if test "x$working_pcre2" = "xyes"; then
AC_MSG_NOTICE([using system PCRE2 library])
else
# pcre2 size wrong or pcre2-config not found
# is it OK to use the included version?
if test "x$included_pcre2" = "xno"; then
# complain
AC_MSG_ERROR([cannot find system pcre2-config, but --without-included-pcre2 was given.
Make sure pcre2-config is installed and available in PATH.
You may need to install the PCRE2 development library for your system.])
else
# use the internal version
included_pcre2=yes
fi
fi
fi
# Re-test as value may have changed.
if test "x$included_pcre2" = "xyes"; then
# Build configure/Makefile for pcre2
AC_MSG_NOTICE([using included PCRE2 library])
# unfortunately these get added to the global configuration
ac_configure_args="$ac_configure_args --disable-pcre2-8 --enable-pcre2-$WCHAR_T_BITS --disable-shared"
AC_CONFIG_SUBDIRS([pcre2-10.21])
PCRE2_CXXFLAGS='-I$(PCRE2_DIR)/src'
PCRE2_LIBS='-L$(PCRE2_LIBDIR) -lpcre2-$(PCRE2_WIDTH)'
# Make the binary depend on the PCRE2 libraries so they get built
EXTRA_PCRE2='$(PCRE2_LIB)'
CXXFLAGS="$CXXFLAGS $PCRE2_CXXFLAGS"
LIBS="$LIBS $PCRE2_LIBS"
fi
# Allow configurable extra directories.
AC_SUBST(extra_completionsdir)
AC_ARG_WITH([extra-completionsdir],
AS_HELP_STRING([--with-extra-completionsdir=DIR],
[path for extra completions]),
[extra_completionsdir=$withval],
[extra_completionsdir='${datadir}/fish/vendor_completions.d'])
AC_SUBST(extra_functionsdir)
AC_ARG_WITH([extra_functionsdir],
AS_HELP_STRING([--with-extra-functionsdir=DIR],
[path for extra functions]),
[extra_functionsdir=$withval],
[extra_functionsdir='${datadir}/fish/vendor_functions.d'])
AC_SUBST(extra_confdir)
AC_ARG_WITH([extra-confdir],
AS_HELP_STRING([--with-extra-confdir=DIR],
[path for extra conf]),
[extra_confdir=$withval],
[extra_confdir='${datadir}/fish/vendor_conf.d'])
# Tell the world what we know.
AC_CONFIG_FILES([Makefile])
AC_OUTPUT AC_OUTPUT
if test ! x$local_found_posix_switch = xyes; then if test ! x$local_found_posix_switch = xyes; then

121
create_wajig_completions.py Executable file
View File

@@ -0,0 +1,121 @@
#!/usr/bin/env python
# -*- python -*-
# Program to generate fish completion function for wajig.
# It runs 'wajig command' and analyzes the output to build a
# completion file which it writes to stdout.
# To use the result, direct stdout to
# ~/.fish.d/completions/wajig.fish.
# Author Reuben Thomas, from Don Rozenberg's bash_completion.py and
# fish's apt-get.fish.
import os
import re
import pprint
pp = pprint.PrettyPrinter()
def escape_quotes(s):
return re.sub('\'', '\\\'', s)
# Run wajig command
f = os.popen('wajig commands', 'r')
lines = f.readlines()
option_patt = r'^-([a-z]*)\|--([a-z]*) +([^ ].*)'
option_patt_r = re.compile(option_patt)
command_patt = r'^([a-z-]*) +([^ ].*)'
command_patt_r = re.compile(command_patt)
os_str = []
os_str.append('')
ol_str = []
ol_str.append('')
oh_str = []
oh_str.append('')
o_i = 0
c_str = []
c_str.append('')
ch_str = []
ch_str.append('')
c_i = 0
for l in lines:
l = l.strip()
if l == '' or l.find(':') > -1 or l.find('Run') == 0:
continue
if l.find('-') == 0:
mo = option_patt_r.search(l)
if mo == None:
continue
os_str[o_i] = mo.group(1)
os_str.append('')
ol_str[o_i] = mo.group(2)
ol_str.append('')
oh_str[o_i] = escape_quotes(mo.group(3))
oh_str.append('')
o_i += 1
else:
mo = command_patt_r.search(l)
if mo == None:
continue
c_str[c_i] = mo.group(1)
c_str.append('')
ch_str[c_i] = escape_quotes(mo.group(2))
ch_str.append('')
c_i += 1
# For debugging, print the commands and options.
#print
#pp.pprint(c_str)
#print
#pp.pprint(os_str)
#print
#pp.pprint(ol_str)
part1 = '''function __fish_wajig_no_subcommand -d (N_ 'Test if wajig has yet to be given the subcommand')
for i in (commandline -opc)
if contains -- $i'''
part2 = '''
return 1
end
end
return 0
end
function __fish_wajig_use_package -d (N_ 'Test if wajig command should have packages as potential completion')
for i in (commandline -opc)
if contains -- $i contains bug build build-depend changelog dependents describe detail hold install installr installrs installs list list-files news package purge purge-depend readme recursive recommended reconfigure reinstall remove remove-depend repackage show showinstall showremove showupgrade size sizes source suggested unhold upgrade versions whatis
return 0
end
end
return 1
end
complete -c wajig -n '__fish_wajig_use_package' -a '(__fish_print_packages)' -d (N_ 'Package')'''
wajig = part1
#add the commands.
for i in range(0, len(c_str) - 1):
wajig = "%s %s" % (wajig, c_str[i])
#add part2
wajig = "%s%s" % (wajig, part2)
#add the options.
wajig = "%s%s" % (wajig, os_str[0].lstrip())
for i in range(1, len(os_str) - 1):
wajig = "%s\ncomplete -c apt-get -s %s -l %s -d (N_ '%s')" % (wajig, os_str[i], ol_str[i], oh_str[i])
#add the commands.
for i in range(0, len(c_str) - 1):
wajig = "%s\ncomplete -f -n '__fish_wajig_no_subcommand' -c wajig -a '%s' -d(N_ '%s')" % (wajig, c_str[i], ch_str[i])
#print it all
print wajig

1
debian/compat vendored
View File

@@ -1 +0,0 @@
8

31
debian/control vendored
View File

@@ -1,31 +0,0 @@
Source: fish
Section: shells
Priority: extra
Maintainer: ridiculous_fish <corydoras@ridiculousfish.com>
Uploaders: David Adam <zanchey@ucc.gu.uwa.edu.au>, Siteshwar Vashisht <siteshwar@gmail.com>
Build-Depends: debhelper (>= 8.0.0), libncurses5-dev, autoconf, autotools-dev, dh-autoreconf, gettext
Standards-Version: 3.9.4
Homepage: http://fishshell.com/
Vcs-Git: git://github.com/fish-shell/fish-shell.git
Vcs-Browser: https://github.com/fish-shell/fish-shell
Package: fish
Architecture: any
Depends: ${shlibs:Depends}, ${misc:Depends}, passwd (>= 4.0.3-10), bc, gettext-base, man-db
Recommends: python (>=2.6), xsel (>=1.2.0), xdg-utils
Description: friendly interactive shell
Fish is a command-line shell for modern systems, focusing on user-friendliness,
sensibility and discoverability in interactive use. The syntax is simple, but
not POSIX compliant.
Package: fish-dbg
Architecture: any
Section: debug
Priority: extra
Depends: fish (= ${binary:Version}), ${misc:Depends}
Description: debugging symbols for friendly interactive shell
Fish is a command-line shell for modern systems, focusing on user-friendliness,
sensibility and discoverability in interactive use. The syntax is simple, but
not POSIX compliant.
.
This package contains the debugging symbols for fish.

83
debian/copyright vendored
View File

@@ -1,83 +0,0 @@
This work was packaged for Debian by David Adam <zanchey@ucc.gu.uwa.edu.au>
on Thu, 14 Jun 2012 20:33:34 +0800, based on work by James Vega
<jamessan@jamessan.com>.
It was downloaded from:
https://github.com/fish-shell/fish-shell
Upstream Authors:
Axel Liljencrantz
ridiculous_fish
Copyright:
Copyright (C) 2005-2008 Axel Liljencrantz
Copyright (C) 2011-2012 ridiculous_fish
License:
Copyright (C) 2005-2008 Axel Liljencrantz
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
MA 02110-1301, USA.
On Debian systems, the complete text of the GNU General
Public License version 2 can be found in "/usr/share/common-licenses/GPL-2".
Fish contains code under the BSD license, namely versions of the
two functions strlcat and strlcpy, modified for use with wide
character strings.
Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
The XSel command, written and copyrighted by Conrad Parker, is
distributed together with, and used by fish. It is released under the MIT
license.
It is Copyright (C) 2001 Conrad Parker <conrad@vergenet.net>
Permission to use, copy, modify, distribute, and sell this software
and its documentation for any purpose is hereby granted without fee,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation. No representations are made about the
suitability of this software for any purpose. It is provided "as is"
without express or implied warranty.
Fish contains code from the glibc library, namely the wcstok function
in fallback.c. This code is licensed under the LGPL.
On Debian systems, the complete text of the GNU Lesser General
Public License can be found in `/usr/share/common-licenses/LGPL'.
The Debian packaging is:
Copyright (C) 2005 James Vega <jamessan@jamessan.com>
Copyright (C) 2012 David Adam <zanchey@ucc.gu.uwa.edu.au>
and is licensed under the GPL version 2, see above.

12
debian/fish.doc-base vendored
View File

@@ -1,12 +0,0 @@
Document: fish
Title: Debian fish Manual
Author: Axel Liljencrantz <axel@liljencrantz.se>
Abstract: This guide documents fish, a shell
geared towards interactive use.
Section: Shells
Format: HTML
Index: /usr/share/doc/fish/index.html
Files: /usr/share/doc/fish/*.html

2
debian/menu vendored
View File

@@ -1,2 +0,0 @@
?package(fish):needs="text" section="Applications/Shells"\
title="fish" command="/usr/bin/fish"

47
debian/postinst vendored
View File

@@ -1,47 +0,0 @@
#!/bin/sh
# postinst script for fish
#
# see: dh_installdeb(1)
set -e
# summary of how this script can be called:
# * <postinst> `configure' <most-recently-configured-version>
# * <old-postinst> `abort-upgrade' <new version>
# * <conflictor's-postinst> `abort-remove' `in-favour' <package>
# <new-version>
# * <postinst> `abort-remove'
# * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
# <failed-install-package> <version> `removing'
# <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package
add_shell() {
if ! type add-shell > /dev/null 2>&1; then
return
fi
add-shell /usr/bin/fish
}
case "$1" in
configure)
add_shell
;;
abort-upgrade|abort-remove|abort-deconfigure)
;;
*)
echo "postinst called with unknown argument \`$1'" >&2
exit 1
;;
esac
# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.
#DEBHELPER#
exit 0

37
debian/postrm vendored
View File

@@ -1,37 +0,0 @@
#!/bin/sh
# postrm script for fish
#
# see: dh_installdeb(1)
set -e
# summary of how this script can be called:
# * <postrm> `remove'
# * <postrm> `purge'
# * <old-postrm> `upgrade' <new-version>
# * <new-postrm> `failed-upgrade' <old-version>
# * <new-postrm> `abort-install'
# * <new-postrm> `abort-install' <old-version>
# * <new-postrm> `abort-upgrade' <old-version>
# * <disappearer's-postrm> `disappear' <overwriter>
# <overwriter-version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package
case "$1" in
purge|remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
;;
*)
echo "postrm called with unknown argument \`$1'" >&2
exit 1
;;
esac
# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.
#DEBHELPER#
exit 0

46
debian/prerm vendored
View File

@@ -1,46 +0,0 @@
#!/bin/sh
# prerm script for fish
#
# see: dh_installdeb(1)
set -e
# summary of how this script can be called:
# * <prerm> `remove'
# * <old-prerm> `upgrade' <new-version>
# * <new-prerm> `failed-upgrade' <old-version>
# * <conflictor's-prerm> `remove' `in-favour' <package> <new-version>
# * <deconfigured's-prerm> `deconfigure' `in-favour'
# <package-being-installed> <version> `removing'
# <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package
remove_shell() {
if ! type remove-shell > /dev/null 2>&1; then
return
fi
remove-shell /usr/bin/fish
}
case "$1" in
remove|deconfigure)
remove_shell
;;
upgrade|failed-upgrade)
;;
*)
echo "prerm called with unknown argument \`$1'" >&2
exit 1
;;
esac
# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.
#DEBHELPER#
exit 0

25
debian/rules vendored
View File

@@ -1,25 +0,0 @@
#!/usr/bin/make -f
# -*- makefile -*-
# Uncomment this to turn on verbose mode.
export DH_VERBOSE=1
# dpkg-dev 1.16.1 doesn't export buildflags
# can be removed once on dh compat level 9
DPKG_EXPORT_BUILDFLAGS = 1
-include /usr/share/dpkg/buildflags.mk
%:
dh $@ --with autotools-dev,autoreconf
override_dh_auto_install:
dh_auto_install --destdir=debian/fish
override_dh_installdocs:
dh_installdocs --link-doc=fish
override_dh_strip:
dh_strip --dbg-package=fish-dbg
# Don't run tests; they don't work until fish is installed
override_dh_auto_test:

View File

@@ -1 +0,0 @@
3.0 (quilt)

View File

@@ -1,264 +0,0 @@
# Formatting guide for fish docs
The fish documentation has been updated to support Doxygen 1.8.7+, and while the main benefit of this change is extensive Markdown support, the addition of a fish lexicon and syntax filter, combined with semantic markup rules allows for automatic formatting enhancements across the HTML user_docs, the developer docs and the man pages.
Initially my motivation was to fix a problem with long options ([Issue #1557](https://github.com/fish-shell/fish-shell/issues/1557) on GitHub), but as I worked on fixing the issue I realised there was an opportunity to simplify, reinforce and clarify the current documentation, hopefully making further contribution easier and cleaner, while allowing the documentation examples to presented more clearly with less author effort.
While the documentation is pretty robust to variations in the documentation source, adherence to the following style guide will help keep the already excellent documention in good shape moving forward.
## Line breaks and wrapping
Contrary to the rest of the fish source code, the documentation greatly benefits from the use of long lines and soft wrapping. It allows paragraphs to be treated as complete blocks by Doxygen, means that the semantic filter can see complete lines when deciding on how to apply syntax highlighting, and means that man pages will consistently wrap to the width of the users console in advanced pagers, such as 'most'.
## Doxygen special commands and aliases
While Markdown syntax forms the basis of the documentation content, there are some exceptions that require the use of Doxygen special commands. On the whole, Doxygen commands should be avoided, especially inline word formatting such as \\c as this would allow Doxygen to make unhelpful assumptions, such as converting double dashes (\--) to n-dashes ().
### Structure: \\page, \\section and \\subsection
Use of Doxygen sections markers are important, as these determine what will be eventually output as a web page, man page or included in the developer docs.
Currently the make process for the documentation is quite convoluted, but basically the HTML docs are produced from a single, compiled file, doc.h. This contains a number of \\page markers that produce the various pages used in the documentation. The format of a \\page mark is:
\page universally_unique_page_id Page title
The source files that contain the page markers are currently:
- __index.hdr.in__: Core documentation
- __commands.hdr.in__: Individual commands
- __tutorial.hdr__: Tutorial
- __design.hdr__: Design document
- __faq.hdr__: Frequently Asked Questions
- __license.hdr__: Fish and 3rd party licences
Unless there is a _VERY_ good reason and developer consensus, new pages should never be added.
The rest of the documentation is structured using \\section and \\subsection markers. Most of the source files (listed above) contain their full content, the exception being commands, which are separated out into source text files in the doc_src directory. These files are concatenated into one file, so each one starts with a \\section declaration. The synopsis, description and examples (if present) are declared as \\subsections. The format of these marks is practically identical to the page mark.
\section universally_unique_section_id Section title
\subsection universally_unique_subsection_id Subsection title
Each page, section and subsection id _must_ be unique across the whole of the documentation, otherwise Doxygen will issue a warning.
### Semantic markup: the \\fish .. \\endfish block
While Doxygen has support for \\code..\\endcode blocks with enhanced markup and syntax colouring, it only understands the core Doxygen languages: C, C++, Objective C, Java, PHP, Python, Tcl and Fortran. To enhance Fish's syntax presentation, use the special \\fish..\\endfish blocks instead.
Text placed in this block will be parsed by Doxygen using the included lexicon filter (see lexicon_filter.in) as a Doxygen input filter. The filter is built during make so that it can pick up information on builtins, functions and shell commands mentioned in completions and apply markup to keywords found inside the \\fish block.
Basically, preformatted plain text inside the \\fish block is fed through the filter and is returned marked up so that Doxygen aliases can convert it back to a presentable form, according to the output document type.
For instance:
`echo hello world`
is transformed into:
`@cmnd{echo} @args{hello} @args{world}`
which is then transformed by Doxygen into an HTML version (`make doc`):
`<span class="command">echo</span> <span class="argument">hello</span> <span class="argument">world</span>`
A man page version (`make share/man`):
__echo__ hello world
And a simple HTML version for the developer docs (`make doc`) and the LATEX/PDF manual (`make doc/refman.pdf`):
`echo hello world`
### Fonts
In older browsers, it was easy to set the fonts used for the three basic type styles (serif, sans-serif and monospace). Modern browsers have removed these options in their respective quests for simplification, assuming the content author will provide suitable styles for the content in the site's CSS, or the end user will provide overriding styles manually. Doxygen's default styling is very simple and most users will just accept this default.
I've tried to use a sensible set of fonts in the documentation's CSS based on 'good' terminal fonts and as a result the firt preference font used throughout the documentation is '[DejaVu](http://dejavu-fonts.org)'. The rationale behaind this is that while DejaVu is getting a little long in the tooth, it still provides the most complete support across serif, sans-serif and monospace styles (giving a well balanced feel and consistent [x-height](http://en.wikipedia.org/wiki/X-height)), has the widest support for extended Unicode characters and has a free, permissive licenses (though it's still incompatible with GPLv2, though arguably less so than the SIL Open Font license, though this is a moot point when using it solely in the docs).
#### Fonts inside \\fish blocks and \`backticks\`
As the point of these contructs is to make fish's syntax clearer to the user, it makes sense to mimic what the user will see in the console, therefore any content is formatted using the monospaced style, specifically monospaced fonts are chosen in the following order:
1. __DejaVu Sans Mono__: Explained above. [[&darr;](http://dejavu-fonts.org)]
2. __Source Code Pro__: Monospaced code font, part of Adobe's free Edge Web Fonts. [[&darr;](https://edgewebfonts.adobe.com)]
3. __Menlo__: Apple supplied variant of DejaVu.
4. __Ubuntu Mono__: Ubuntu Linux's default monospaced font. [[&darr;](http://font.ubuntu.com)]
5. __Consolas__: Modern Microsoft supplied console font.
6. __Monaco__: Apple supplied console font since 1984!
7. __Lucida Console__: Generic mono terminal font, standard in many OS's and distros.
8. __monospace__: Catchall style. Chooses default monospaced font, often Courier.
9. __fixed__: As above, more often used on mobile devices.
#### General Fonts
1. __DejaVu Sans__: As above.[[&darr;](http://dejavu-fonts.org)]
2. __Roboto__: Elegant Google free font and is Doxygen's default [[&darr;](http://www.google.com/fonts/specimen/Roboto)]
3. __Lucida Grande__: Default Apple OS X content font.
4. __Calibri__: Default Microsoft Office font (since 2007).
5. __Verdana__: Good general font found in a lot of OSs.
6. __Helvetica Neue__: Better spaced and balanced Helvetica/Arial variant.
7. __Helvetica__: Standard humanist typeface found almost everywhere.
8. __Arial__: Microsoft's Helvetica.
9. __sans-serif__: Catchall style. Chooses default sans-serif typeface, often Helvetica.
The ordering of the fonts is important as it's designed to allow the documentation to settle into a number of different identities according to the fonts available. If you have the complete DejaVu family installed, then the docs are presented using that, and if your Console is set up to use the same fonts, presentation will be completely consistent.
On OS X, with nothing extra installed, the docs will default to Menlo and Lucida Grande giving a Mac feel. Under Windows, it will default to using Consolas and Calibri on recent versions, giving a modern Windows style.
#### Other sources:
- [Font Squirrel](http://www.fontsquirrel.com): Good source of open source font packages.
### Choosing a CLI style: using a \\fish{style} block
By default, when output as HTML, a \\fish block uses syntax colouring suited to the style of the documentation rather than trying to mimic the terminal. The block has a light, bordered background and a colour scheme that 'suggests' what the user would see in a console.
Additional stying can be applied adding a style declaration:
\fish{additional_style [another_style...]}
...
\endfish
This will translate to classes applied to the `<div>` tag, like so:
<div class="fish additional_style another_style">
...
</div>
The various classes are defined in `doc_src/user_doc.css` and new style can be simply added
The documentation currently defines a couple of additional styles:
- __cli-dark__: Used in the _tutorial_ and _FAQ_ to simulate a dark background terminal, with fish's default colours (slightly tweaked for legibility in the browser).
- __synopsis__: A simple colour theme helpful for displaying the logical 'summary' of a command's syntax, options and structure.
## Markdown
Apart from the exceptions discussed above, the rest of the documentation now supports the use of Markdown. As such the use of Doxygen special commands for HTML tags is unnecessary.
There are a few exceptions and extensions to the Markdown [standard](http://daringfireball.net/projects/markdown/) that are documented in the Doxygen [documentation](http://www.stack.nl/~dimitri/doxygen/manual/markdown.html).
### \`Backticks\`
As is standard in Markdown and 'Github Flavoured Markdown' (GFM), backticks can be used to denote inline technical terms in the documentation, `like so`. In the documentation this will set the font to the monospaced 'console' typeface and will cause the enclosed term to stand out.
However, fenced code blocks using 4 spaces or 3 backticks (\`\`\`) should be avoided as Doxygen will interpret these as \\code blocks and try to apply standard syntax colouring, which doesn't work so well for fish examples. Use `\fish..\endfish` blocks instead.
### Lists
Standard Markdown list rules apply, but as Doxygen will collapse white space on output, combined with the use of long lines, it's a good idea to include an extra new line between long list items to assist future editing.
## Special cases
The following can be used in \\fish blocks to render some fish scenarios. These are mostly used in the tutorial when an interactive situation needs to be displayed.
### Custom formatting tags
- `<s>`: auto\<s\>suggestion\</s\>.
- `<m>`: \<m\>Matched\</m\> items, such as tab completions.
- `<sm>`: Matched items \<sm\>searched\<sm\> for, like grep results.
- `<error>`: \<error\>This would be shown as an error.\</error\>
- `<asis>`: \<asis\>This test will not be parsed for fish markup.\</asis\>
- `<outp>`: \<outp\>This would be rendered as command/script output.\</outp\>
- `<bs>`: Render the contents with a preceding backslash. Useful when presenting output.
- `{{` and `}}`: Required when wanting curly braces in regular expression example.
### Prompts and cursors
- `>_`: Display a basic prompt.
- `~>_`: Display a prompt with a the home directory as the current working directory.
- `___` (3 underscores): Display a cursor.
### Keyboard shortcuts: @key{} and @cursor_key{}
Graphical keyboard shortcuts can be defined using the following special commands. These allow for the different text requirements across the html and man pages. The HTML uses CSS to create a keyboard style, whereas the man page would display the key as text.
- `@key{lable}`
Displays a key with a purely textual lable, such as: 'Tab', 'Page Up', 'Page Down', 'Home', 'End', 'F1', 'F19' and so on.
- `@key{modifier,lable}`
Displays a keystroke requiring the use of a 'modifier' key, such as 'Control-A', 'Shift-X', 'Alt-Tab' etc.
- `@key{modifier,entity,lable}`
Displays a keystroke using a graphical entity, such as an arrow symbol for cursor key based shortcuts.
- `@cursor_key{entity,lable}`
A special case for cursor keys, when no modifier is needed. i.e. `@cursor_key{&uarr;,up}` for the up arrow key.
Some useful Unicode/HTML5 entities:
- Up arrow: `&uarr;`
- Down arrow: `&darr;`
- Left arrow: `&larr;`
- Right arrow `&rarr;`
- Shift: `&#8679;`
- Tab: `&rarrb;`
- Mac option: `&#8997;`
- Mac command: `&#8984;`
## Notes
### Doxygen
Tested on:
- Ubuntu 14.04 with Doxygen 1.8.8, built from [GitHub source](https://github.com/doxygen/doxygen.git).
- CentOS 6.5 with Doxygen 1.8.8, built from [GitHub source](https://github.com/doxygen/doxygen.git).
- Mac OS X 10.9 with Homebrew install Doxygen 1.8.7 and 1.8.8.
Graphviz was also installed in all the above testing.
Doxygen 1.8.6 and lower do not have the \\htmlonly[block] directive which fixes a multitude of problems in the rendering of the docs. In Doxygen 1.8.7 the list of understood HTML entities was greatly increased. I tested earlier versions and many little issues returned.
As fish ships with pre-built documentation, I don't see this as an issue.
### Updated Configure/Makefile
- Tested on Ubuntu 14.04, CentOS 6.5 and Mac OS X 10.9.
- Makefile has GNU/BSD sed/grep detection.
### HTML output
- The output HTML is HTML5 compliant, but should quickly and elegantly degrade on older browsers without losing basic structure.
- The CSS avoids the use or browser specific extenstions (i.e. -webkit, -moz etc), using the W3C HTML5 standard instead.
- It's been tested in Chrome 37.0 and Firefox 32.0 on Mac OS X 10.9 (+Safari 7), Windows 8.1 (+Internet Explorer 11) and Ubuntu Desktop 14.04.
- My assumption is basically that if someone cares enough to want to install fish, they'll be keeping a browser current.
### Man page output
- Tested on Ubuntu 14.04, CentOS 6.5 and Mac OS X 10.9.
- Output is substantially cleaner.
- Tested in cat, less, more and most pagers using the following fish script:
```
function manTest --description 'Test manpage' --argument page
set -l pager
for i in $argv
switch $i
case "-l"
set pager -P '/usr/bin/less -is'
case "-m"
set pager -P '/usr/bin/more -s'
case "-c"
set pager -P '/bin/cat'
end
end
man $pager ~/Projects/OpenSource/fish-shell/share/man/man1/$page.1
end
# Assumes 'most' is the default system pager.
# NOT PORTABLE! Paths would be need to be updated on other systems.
```
### Developer docs and LATEX/PDF output
- HTML developer docs tested on Ubuntu 14.04, CentOS 6.5 and Mac OS X 10.9.
- LATEX/PDF reference manual tested on Mac OS X 10.9 using MacTEX. PDF production returns an error (due to Doxygen's use of an outdated 'float' package), but manual PDF output is ok.
### Future changes
1. The documentation creation process would be better if it could be modularised further and moved out of the makefile into a number of supporting scripts. This would allow both the automake and Xcode build processes to use the documentation scripts directly.
2. Remove the Doxygen dependency entirely for the user documentation. This would be very acheivable now that the bulk of the documentation is in Markdown.
3. It would be useful to gauge what parts of the documentation are actually used by users. Judging by the amount of 'missing comment' errors during the developer docs build phase, this aspect of the docs has been rather neglected. If it is not longer used or useful, then this could change the future direction of the documentation and significantly streamline the process.
#### Author: Mark Griffiths [@GitHub](https://github.com/MarkGriffiths)

View File

@@ -1,46 +0,0 @@
\section abbr abbr - manage fish abbreviations
\subsection abbr-synopsis Synopsis
\fish{synopsis}
abbr -a word phrase...
abbr -s
abbr -l
abbr -e word
\endfish
\subsection abbr-description Description
`abbr` manipulates the list of abbreviations that fish will expand.
Abbreviations are user-defined character sequences or words that are replaced with longer phrases after they are entered. For example, a frequently-run command such as `git checkout` can be abbreviated to `gco`. After entering `gco` and pressing @key{Space} or @key{Enter}, the full text `git checkout` will appear in the command line.
Abbreviations are stored using universal variables. You can create abbreviations directly on the command line, and they will be saved automatically. Calling `abbr -a` in config.fish will lead to slightly worse startup performance.
The following parameters are available:
- `-a WORD PHRASE` or `--add WORD PHRASE` Adds a new abbreviation, where WORD will be expanded to PHRASE.
- `-s` or `--show` Show all abbreviated words and their expanded phrases in a manner suitable for export and import.
- `-l` or `--list` Lists all abbreviated words.
- `-e WORD` or `--erase WORD` Erase the abbreviation WORD.
Note: fish version 2.1 supported `-a WORD=PHRASE`. This syntax is now deprecated but will still be converted.
\subsection abbr-example Examples
\fish
abbr -a gco git checkout
\endfish
Add a new abbreviation where `gco` will be replaced with `git checkout`.
\fish
abbr -e gco
\endfish
Erase the `gco` abbreviation.
\fish
ssh another_host abbr -s | source
\endfish
Import the abbreviations defined on another_host over SSH.

View File

@@ -1,40 +1,34 @@
\section alias alias - create a function \section alias alias - create a function
\subsection alias-synopsis Synopsis \subsection alias-synopsis Synopsis
\fish{synopsis} <pre>alias NAME DEFINITION
alias NAME DEFINITION alias NAME=DEFINITION</pre>
alias NAME=DEFINITION
\endfish
\subsection alias-description Description \subsection alias-description Description
`alias` is a simple wrapper for the `function` builtin. It exists for backwards compatibility with Posix shells. For other uses, it is recommended to define a <a href='#function'>function</a>. \c alias is a simple wrapper for the \c function builtin.
It exists for backwards compatibility with Posix
shells. For other uses, it is recommended to define a <a
href='#function'>function</a>.
`fish` does not keep track of which functions have been defined using `alias`. They must be erased using `functions -e`. \c fish does not keep track of which functions have been defined using
\c alias. They must be erased using <code>functions -e</code>.
- `NAME` is the name of the alias - NAME is the name of the alias
- DEFINITION is the actual command to execute. The string " $argv" will be appended.
- `DEFINITION` is the actual command to execute. The string `$argv` will be appended.
You cannot create an alias to a function with the same name. You cannot create an alias to a function with the same name.
Note that spaces need to be escaped in the call to alias just like in the commandline _even inside the quotes_.
\subsection alias-example Example \subsection alias-example Example
The following code will create `rmi`, which runs `rm` with additional arguments on every invocation. The following code will create \c rmi, which runs \c rm with additional
arguments on every invocation.
\fish <code>alias rmi "rm -i"</code>
alias rmi "rm -i"
# This is equivalent to entering the following function: This is equivalent to entering the following function:
function rmi <pre>function rmi
rm -i $argv rm -i $argv
end end</pre>
# This needs to have the spaces escaped or "Chrome.app..." will be seen as an argument to "/Applications/Google":
alias chrome='/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome banana'
\endfish

View File

@@ -1,25 +1,27 @@
\section and and - conditionally execute a command \section and and - conditionally execute a command
\subsection and-synopsis Synopsis \subsection and-synopsis Synopsis
\fish{synopsis} <tt>COMMAND1; and COMMAND2</tt>
COMMAND1; and COMMAND2
\endfish
\subsection and-description Description \subsection and-description Description
`and` is used to execute a command if the current exit status (as set by the previous command) is 0. \c and is used to execute a command if the current exit
status (as set by the last previous command) is 0.
`and` statements may be used as part of the condition in an <a href="#if">`and`</a> or <a href="#while">`while`</a> block. See the documentation \c and does not change the current exit status.
for <a href="#if">`if`</a> and <a href="#while">`while`</a> for examples.
`and` does not change the current exit status. The exit status of the last foreground command to exit can always be accessed using the <a href="index.html#variables-status">$status</a> variable.
The exit status of the last foreground command to exit can always be
accessed using the <a href="index.html#variables-status">$status</a>
variable.
\subsection and-example Example \subsection and-example Example
The following code runs the `make` command to build a program. If the build succeeds, `make`'s exit status is 0, and the program is installed. If either step fails, the exit status is 1, and `make clean` is run, which removes the files created by the build process. The following code runs the \c make command to build a program. If the
build succeeds, <code>make</code>'s exit status is 0, and the program is installed. If either step fails,
the exit status is 1, and <tt>make clean</tt> is run, which removes the files created by the.
build process.
\fish <pre>
make; and make install; or make clean make; and make install; or make clean
\endfish </pre>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

View File

@@ -1,45 +1,49 @@
\section begin begin - start a new block of code \section begin begin - start a new block of code
\subsection begin-synopsis Synopsis \subsection begin-synopsis Synopsis
\fish{synopsis} <tt>begin; [COMMANDS...;] end</tt>
begin; [COMMANDS...;] end
\endfish
\subsection begin-description Description \subsection begin-description Description
`begin` is used to create a new block of code. \c begin is used to create a new block of code.
The block is unconditionally executed. `begin; ...; end` is equivalent to `if true; ...; end`. The block
is unconditionally executed. <code>begin; ...; end</tt> is equivalent
to <tt>if true; ...; end</tt>.
`begin` is used to group a number of commands into a block. This allows the introduction of a new variable scope, redirection of the input or output of a set of commands as a group, or to specify precedence when using the conditional commands like `and`. \c begin is used to group a number of commands into a block.
This allows the introduction of a new variable scope, redirection of the input or
`begin` does not change the current exit status. output of a set of commands as a group, or to specify precedence when
using the conditional commands like \c and.
\c begin does not change the current exit status.
\subsection begin-example Example \subsection begin-example Example
The following code sets a number of variables inside of a block scope. Since the variables are set inside the block and have local scope, they will be automatically deleted when the block ends. The following code sets a number of variables inside of a block
scope. Since the variables are set inside the block and have local
scope, they will be automatically deleted when the block ends.
\fish <pre>
begin begin
set -l PIRATE Yarrr set -l PIRATE Yarrr
... ...
end end
# This will not output anything, since the PIRATE variable went out
# of scope at the end of the block
echo $PIRATE echo $PIRATE
# This will not output anything, since the PIRATE variable </pre>
# went out of scope at the end of the block
\endfish
In the following code, all output is redirected to the file out.html. In the following code, all output is redirected to the file out.html.
\fish <pre>
begin begin
echo $xml_header echo $xml_header
echo $html_header echo $html_header
if test -e $file if test -e $file
... ...
end end
... ...
end > out.html
\endfish end &gt; out.html
</pre>

View File

@@ -1,17 +1,17 @@
\section bg bg - send jobs to background \section bg bg - send jobs to background
\subsection bg-synopsis Synopsis \subsection bg-synopsis Synopsis
\fish{synopsis} <tt>bg [PID...]</tt>
bg [PID...]
\endfish
\subsection bg-description Description \subsection bg-description Description
`bg` sends <a href="index.html#syntax-job-control">jobs</a> to the background, resuming them if they are stopped. A background job is executed simultaneously with fish, and does not have access to the keyboard. If no job is specified, the last job to be used is put in the background. If PID is specified, the jobs with the specified process group IDs are put in the background. \c bg sends <a href="index.html#syntax-job-control">jobs</a> to the background, resuming them if they are stopped. A background job is
executed simultaneously with fish, and does not have access to the
keyboard. If no job is specified, the last job to be used is put in the background. If PID is specified, the jobs with the specified process group IDs are put in the background.
The PID of the desired process is usually found by using <a href="index.html#expand-process">process expansion</a>. The PID of the desired process is usually found by using <a href="index.html#expand-process">process expansion</a>.
\subsection bg-example Example \subsection bg-example Example
`bg %1` will put the job with job ID 1 in the background. <tt>bg \%1</tt> will put the job with job ID 1 in the background.

View File

@@ -1,156 +1,64 @@
\section bind bind - handle fish key bindings \section bind bind - handle fish key bindings
\subsection bind-synopsis Synopsis \subsection bind-synopsis Synopsis
\fish{synopsis} <tt>bind [OPTIONS] SEQUENCE COMMAND</tt>
bind [(-M | --mode) MODE] [(-m | --sets-mode) NEW_MODE]
[(-k | --key)] SEQUENCE COMMAND [COMMAND...]
bind [(-M | --mode) MODE] [(-k | --key)] SEQUENCE
bind (-K | --key-names) [(-a | --all)]
bind (-f | --function-names)
bind (-e | --erase) [(-M | --mode) MODE]
(-a | --all | [(-k | --key)] SEQUENCE [SEQUENCE...])
\endfish
\subsection bind-description Description \subsection bind-description Description
`bind` adds a binding for the specified key sequence to the specified command. <tt>bind</tt> adds a binding for the specified key sequence to the
specified command.
SEQUENCE is the character sequence to bind to. These should be written as <a href="index.html#escapes">fish escape sequences</a>. For example, because pressing the Alt key and another character sends that character prefixed with an escape character, Alt-based key bindings can be written using the `\e` escape. For example, @key{Alt,w} can be written as `\ew`. The control character can be written in much the same way using the `\c` escape, for example @key{Control,X} (^X) can be written as `\cx`. Note that Alt-based key bindings are case sensitive and Control-based key bindings are not. This is a constraint of text-based terminals, not `fish`. SEQUENCE is the character sequence to bind to. These should be written as
<a href="index.html#escapes">fish escape sequences</a>. For example, because pressing
the Alt key and another character sends that character prefixed with
an escape character, Alt-based key bindings can be written using the
\c \\e escape. For example, Alt-w can be written as
<tt>\\ew</tt>. The control character can be written in much the same way
using the \c \\c escape, for example Control-x (^X) can be written as
<tt>\\cx</tt>. Note that Alt-based key bindings are case sensitive and
Control-based key bindings are not. This is a constraint of text-based
termainls, not \c fish.
The default key binding can be set by specifying a `SEQUENCE` of the empty string (that is, ```''``` ). It will be used whenever no other binding matches. For most key bindings, it makes sense to use the `self-insert` function (i.e. ```bind '' self-insert```) as the default keybinding. This will insert any keystrokes not specifically bound to into the editor. Non- printable characters are ignored by the editor, so this will not result in control sequences being printable. The default key binding can be set by specifying a SEQUENCE of the empty
string (that is, <code>''</code>). It will be used whenever no
other binding matches. For most key bindings, it makes sense to use
the \c self-insert function (i.e. <tt>bind '' self-insert</tt> as the
default keybinding. This will insert any keystrokes not specifically
bound to into the editor. Non-printable characters are ignored by the
editor, so this will not result in control sequences being
printable.
If the `-k` switch is used, the name of the key (such as 'down', 'up' or 'backspace') is used instead of a sequence. The names used are the same as the corresponding curses variables, but without the 'key_' prefix. (See `terminfo(5)` for more information, or use `bind --key-names` for a list of all available named keys.) If the -k switch is used, the name of the key (such as down, up or
backspace) is used instead of a sequence. The names used are the same
as the corresponding curses variables, but without the 'key_'
prefix. (See \c terminfo(5) for more information, or use <tt>bind
--key-names</tt> for a list of all available named keys.)
`COMMAND` can be any fish command, but it can also be one of a set of special input functions. These include functions for moving the cursor, operating on the kill-ring, performing tab completion, etc. Use `bind --function-names` for a complete list of these input functions. COMMAND can be any fish command, but it can also be one of a set of
special input functions. These include functions for moving the
cursor, operating on the kill-ring, performing tab completion,
etc. Use 'bind --function-names' for a complete list of these input
functions.
When `COMMAND` is a shellscript command, it is a good practice to put the actual code into a <a href="#function">function</a> and simply bind to the function name. This way it becomes significantly easier to test the function while editing, and the result is usually more readable as well. When COMMAND is a shellscript command, it is a good practice to put
the actual code into a <a href="#function">function</a> and simply
bind to the function name. This way it becomes significantly easier to
test the function while editing, and the result is usually more
readable as well.
If such a script produces output, the script needs to finish by calling `commandline -f repaint` in order to tell fish that a repaint is in order. Key bindings are not saved between sessions by default. To save custom
keybindings, edit the \c fish_user_key_bindings function and insert the
When multiple `COMMAND`s are provided, they are all run in the specified order when the key is pressed. appropirate \c bind statements.
If no `SEQUENCE` is provided, all bindings (or just the bindings in the specified `MODE`) are printed. If `SEQUENCE` is provided without `COMMAND`, just the binding matching that sequence is printed.
Key bindings are not saved between sessions by default. **Bare `bind` statements in <a href="index.html#initialization">config.fish</a> won't have any effect because it is sourced before the default keybindings are setup.** To save custom keybindings, put the `bind` statements into a function called `fish_user_key_bindings`, which will be <a href="tutorial.html#tut_autoload">autoloaded</a>.
Key bindings may use "modes", which mimics Vi's modal input behavior. The default mode is "default", and every bind applies to a single mode. The mode can be viewed/changed with the `$fish_bind_mode` variable.
The following parameters are available: The following parameters are available:
- `-k` or `--key` Specify a key name, such as 'left' or 'backspace' instead of a character sequence - <tt>-k</tt> or <tt>--key</tt> Specify a key name, such as 'left' or 'backspace' instead of a character sequence
- <tt>-K</tt> or <tt>--key-names</tt> Display a list of available key names
- `-K` or `--key-names` Display a list of available key names. Specifying `-a` or `--all` includes keys that don't have a known mapping - <tt>-f</tt> or <tt>--function-names</tt> Display a list of available input functions
- `-f` or `--function-names` Display a list of available input functions
- `-M MODE` or `--mode MODE` Specify a bind mode that the bind is used in. Defaults to "default"
- `-m NEW_MODE` or `--sets-mode NEW_MODE` Change the current mode to `NEW_MODE` after this binding is executed
- `-e` or `--erase` Erase the binding with the given sequence and mode instead of defining a new one. Multiple sequences can be specified with this flag. Specifying `-a` or `--all` with `-M` or `--mode` erases all binds in the given mode regardless of sequence. Specifying `-a` or `--all` without `-M` or `--mode` erases all binds in all modes regardless of sequence.
- `-a` or `--all` See `--erase` and `--key-names`
The following special input functions are available:
- `accept-autosuggestion`, accept the current autosuggestion completely
- `backward-char`, moves one character to the left
- `backward-bigword`, move one whitespace-delimited word to the left
- `backward-delete-char`, deletes one character of input to the left of the cursor
- `backward-kill-bigword`, move the whitespace-delimited word to the left of the cursor to the killring
- `backward-kill-line`, move everything from the beginning of the line to the cursor to the killring
- `backward-kill-path-component`, move one path component to the left of the cursor (everything from the last "/" or whitespace exclusive) to the killring
- `backward-kill-word`, move the word to the left of the cursor to the killring
- `backward-word`, move one word to the left
- `beginning-of-history`, move to the beginning of the history
- `beginning-of-line`, move to the beginning of the line
- `begin-selection`, start selecting text
- `capitalize-word`, make the current word begin with a capital letter
- `complete`, guess the remainder of the current token
- `complete-and-search`, invoke the searchable pager on completion options
- `delete-char`, delete one character to the right of the cursor
- `downcase-word`, make the current word lowercase
- `end-of-history`, move to the end of the history
- `end-of-line`, move to the end of the line
- `end-selection`, end selecting text
- `forward-bigword`, move one whitespace-delimited word to the right
- `forward-char`, move one character to the right
- `forward-word`, move one word to the right
- `history-search-backward`, search the history for the previous match
- `history-search-forward`, search the history for the next match
- `kill-bigword`, move the next whitespace-delimited word to the killring
- `kill-line`, move everything from the cursor to the end of the line to the killring
- `kill-selection`, move the selected text to the killring
- `kill-whole-line`, move the line to the killring
- `kill-word`, move the next word to the killring
- `suppress-autosuggestion`, remove the current autosuggestion
- `swap-selection-start-stop`, go to the other end of the highlighted text without changing the selection
- `transpose-chars`, transpose two characters to the left of the cursor
- `transpose-words`, transpose two words to the left of the cursor
- `upcase-word`, make the current word uppercase
- `yank`, insert the latest entry of the killring into the buffer
- `yank-pop`, rotate to the previous entry of the killring
\subsection bind-example Examples \subsection bind-example Examples
\fish <tt>bind \\cd 'exit'</tt> causes \c fish to exit when Control-d is pressed.
bind \cd 'exit'
\endfish
Causes `fish` to exit when @key{Control,D} is pressed.
\fish <tt>bind -k ppage history-search-backward</tt> performs a history search when the Page Up key is pressed.
bind -k ppage history-search-backward
\endfish
Performs a history search when the @key{Page Up} key is pressed.
\fish
set -g fish_key_bindings fish_vi_key_bindings
bind -M insert \cc kill-whole-line force-repaint
\endfish
Turns on Vi key bindings and rebinds @key{Control,C} to clear the input line.
\subsection special-case-escape Special Case: The escape Character
The escape key can be used standalone, for example, to switch from insertion mode to normal mode when using Vi keybindings. Escape may also be used as a "meta" key, to indicate the start of an escape sequence, such as function or arrow keys. Custom bindings can also be defined that begin with an escape character.
fish waits for a period after receiving the escape character, to determine whether it is standalone or part of an escape sequence. While waiting, additional key presses make the escape key behave as a meta key. If no other key presses come in, it is handled as a standalone escape. The waiting period is set to 300 milliseconds (0.3 seconds) in the default key bindings and 10 milliseconds in the vi key bindings. It can be configured by setting the `fish_escape_delay_ms` variable to a value between 10 and 5000 ms. It is recommended that this be a universal variable that you set once from an interactive session.
Note: fish 2.2.0 and earlier used a default of 10 milliseconds, and provided no way to configure it. That effectively made it impossible to use escape as a meta key.

View File

@@ -1,41 +1,40 @@
\section block block - temporarily block delivery of events \section block block - temporarily block delivery of events
\subsection block-synopsis Synopsis \subsection block-synopsis Synopsis
\fish{synopsis} <tt>block [OPTIONS...]</tt>
block [OPTIONS...]
\endfish
\subsection block-description Description \subsection block-description Description
`block` prevents events triggered by `fish` or the <a href="commands.html#emit">`emit`</a> command from being delivered and acted upon while the block is in place. \c block prevents events triggered by \c fish or the
<a href="commands.html#emit"><code>emit</code></a> command from
being delivered and acted upon while the block is in place.
In functions, `block` can be useful while performing work that should not be interrupted by the shell. In functions, \c block can be useful while performing work that
should not be interrupted by the shell.
The block can be removed. Any events which triggered while the block was in place will then be delivered. The block can be removed. Any events which triggered while the
block was in place will then be delivered.
Event blocks should not be confused with code blocks, which are created with `begin`, `if`, `while` or `for` Event blocks should not be confused with code blocks, which are created
with <code>begin</code>, <code>if</code>, <code>while</code> or
<code>for</code>
The following parameters are available: The following parameters are available:
- `-l` or `--local` Release the block automatically at the end of the current innermost code block scope - <tt>-l</tt> or <tt>--local</tt> Release the block automatically at the end of the current innermost code block scope
- <tt>-g</tt> or <tt>--global</tt> Never automatically release the lock
- `-g` or `--global` Never automatically release the lock - <tt>-e</tt> or <tt>--erase</tt> Release global block
- `-e` or `--erase` Release global block
\subsection block-example Example \subsection block-example Example
\fish <pre>
# Create a function that listens for events # Create a function that listens for events
function --on-event foo foo; echo 'foo fired'; end function --on-event foo foo; echo 'foo fired'; end
# Block the delivery of events # Block the delivery of events
block -g block -g
emit foo emit foo
# No output will be produced # No output will be produced
block -e block -e
# 'foo fired' will now be printed # 'foo fired' will now be printed
\endfish </pre>

View File

@@ -1,9 +0,0 @@
This directory is for images relevant to the fish brand.
The logo.psd and logo.svg files were created by Steve Stagg
(http://github.com/stestagg). They were uploaded to SickerMule by Andrei
Zvonimir Crnković (https://github.com/andreicek). See
https://www.stickermule.com/marketplace/tags/shell
https://www.stickermule.com/marketplace/3507-fish-shell-sticker-die-cut
https://www.stickermule.com/marketplace/3508-fish-shell-sticker-square-cut

Binary file not shown.

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 109 KiB

View File

@@ -1,25 +1,22 @@
\section break break - stop the current inner loop \section break break - stop the current inner loop
\subsection break-synopsis Synopsis \subsection break-synopsis Synopsis
\fish{synopsis} <tt>LOOP_CONSTRUCT; [COMMANDS...] break; [COMMANDS...] end</tt>
LOOP_CONSTRUCT; [COMMANDS...] break; [COMMANDS...] end
\endfish
\subsection break-description Description \subsection break-description Description
`break` halts a currently running loop, such as a <a href="#for">for</a> loop or a <a href="#while">while</a> loop. It is usually added inside of a conditional block such as an <a href="#if">if</a> statement or a <a href="#switch">switch</a> statement. \c break halts a currently running loop, such as a <a href="#for">for</a> loop or a <a href="#while">while</a> loop. It is usually added inside of a conditional block such as an <a href="#if">if</a> statement or a <a href="#switch">switch</a> statement.
There are no parameters for `break`.
There are no parameters for <code>break</code>.
\subsection break-example Example \subsection break-example Example
The following code searches all .c files for "smurf", and halts at the first occurrence. The following code searches all .c files for "smurf", and halts at the first occurrence.
\fish <pre>
for i in *.c for i in *.c
if grep smurf $i if grep smurf $i
echo Smurfs are present in $i echo Smurfs are present in $i
break break
end end
end end
\endfish </pre>

View File

@@ -1,14 +1,14 @@
\section breakpoint breakpoint - Launch debug mode \section breakpoint breakpoint - Launch debug mode
\subsection breakpoint-synopsis Synopsis \subsection breakpoint-synopsis Synopsis
\fish{synopsis} <tt>breakpoint</tt>
breakpoint
\endfish
\subsection breakpoint-description Description \subsection breakpoint-description Description
`breakpoint` is used to halt a running script and launch an interactive debugging prompt. \c breakpoint is used to halt a running script and launch
an interactive debugging prompt.
For more details, see <a href="index.html#debugging">Debugging fish scripts</a> in the `fish` manual. For more details, see <a href="index.html#debugging">Debugging fish
scripts</a> in the \c fish manual.
There are no parameters for `breakpoint`. There are no parameters for <code>breakpoint</code>.

View File

@@ -1,22 +1,16 @@
\section builtin builtin - run a builtin command \section builtin builtin - run a builtin command
\subsection builtin-synopsis Synopsis \subsection builtin-synopsis Synopsis
\fish{synopsis} <tt>builtin BUILTINNAME [OPTIONS...]</tt>
builtin BUILTINNAME [OPTIONS...]
\endfish
\subsection builtin-description Description \subsection builtin-description Description
`builtin` forces the shell to use a builtin command, rather than a function or program. \c builtin forces the shell to use a builtin command, rather than a function or program.
The following parameters are available: The following parameters are available:
- `-n` or `--names` List the names of all defined builtins - <tt>-n</tt> or <tt>--names</tt> List the names of all defined builtins
\subsection builtin-example Example \subsection builtin-example Example
\fish <tt>builtin jobs</tt> executes the jobs builtin, even if a function named jobs exists.
builtin jobs
# executes the jobs builtin, even if a function named jobs exists
\endfish

View File

@@ -1,27 +1,35 @@
\section case case - conditionally execute a block of commands \section case case - conditionally execute a block of commands
\subsection case-synopsis Synopsis \subsection case-synopsis Synopsis
\fish{synopsis} <tt>switch VALUE; [case [WILDCARD...]; [COMMANDS...]; ...] end</tt>
switch VALUE; [case [WILDCARD...]; [COMMANDS...]; ...] end
\endfish
\subsection case-description Description \subsection case-description Description
`switch` performs one of several blocks of commands, depending on whether a specified value equals one of several wildcarded values. `case` is used together with the `switch` statement in order to determine which block should be executed. \c switch performs one of several blocks of commands, depending on whether
a specified value equals one of several wildcarded values. \c case is used
together with the \c switch statement in order to determine which block should
be executed.
Each `case` command is given one or more parameters. The first `case` command with a parameter that matches the string specified in the switch command will be evaluated. `case` parameters may contain wildcards. These need to be escaped or quoted in order to avoid regular wildcard expansion using filenames. Each \c case command is given one or more parameters. The first \c case
command with a parameter that matches the string specified in the
switch command will be evaluated. \c case parameters may contain
wildcards. These need to be escaped or quoted in order to avoid
regular wildcard expansion using filenames.
Note that fish does not fall through on case statements. Only the first matching case is executed. Note that fish does not fall through on case statements. Only the
first matching case is executed.
Note that command substitutions in a case statement will be evaluated even if its body is not taken. All substitutions, including command substitutions, must be performed before the value can be compared against the parameter.
Note that command substitutions in a case statement will be
evaluated even if its body is not taken. All substitutions, including
command substitutions, must be performed before the value can be compared
against the parameter.
\subsection case-example Example \subsection case-example Example
If the variable \$animal contains the name of an animal, the following If the variable \$animal contains the name of an animal, the following
code would attempt to classify it: code would attempt to classify it:
\fish <pre>
switch $animal switch $animal
case cat case cat
echo evil echo evil
@@ -35,8 +43,8 @@ switch $animal
case '*' case '*'
echo I have no idea what a $animal is echo I have no idea what a $animal is
end end
\endfish </pre>
If the above code was run with `$animal` set to `whale`, the output If the above code was run with \c \$animal set to \c whale, the output
would be `mammal`. would be \c mammal.

View File

@@ -1,27 +1,24 @@
\section cd cd - change directory \section cd cd - change directory
\subsection cd-synopsis Synopsis \subsection cd-synopsis Synopsis
\fish{synopsis} <tt>cd [DIRECTORY]</tt>
cd [DIRECTORY]
\endfish
\subsection cd-description Description \subsection cd-description Description
`cd` changes the current working directory. \c cd changes the current working directory.
If `DIRECTORY` is supplied, it will become the new directory. If no parameter is given, the contents of the `HOME` environment variable will be used. If \c DIRECTORY is supplied, it will become the new directory. If no parameter
is given, the contents of the \c HOME environment variable will be used.
If `DIRECTORY` is a relative path, the paths found in the `CDPATH` environment variable array will be tried as prefixes for the specified path. If \c DIRECTORY is a relative path, the paths found in the
\c CDPATH environment variable array will be tried as prefixes for the specified
path.
Note that the shell will attempt to change directory without requiring `cd` if the name of a directory is provided (starting with `.`, `/` or `~`, or ending with `/`). Note that the shell will attempt to change directory without requiring \c cd
if the name of a directory is provided (starting with '.', '/' or '~').
Fish also ships a wrapper function around the builtin `cd` that understands `cd -` as changing to the previous directory. See also <a href="commands.html#prevd">`prevd`</a>. This wrapper function maintains a history of the 25 most recently visited directories in the `$dirprev` and `$dirnext` global variables.
\subsection cd-example Examples \subsection cd-example Examples
\fish \c cd changes the working directory to your home directory.
cd
# changes the working directory to your home directory.
cd /usr/src/fish-shell <code>cd /usr/src/fish-shell</code> changes the working directory to
# changes the working directory to /usr/src/fish-shell <code>/usr/src/fish-shell</code>.
\endfish

View File

@@ -1,24 +1,12 @@
\section command command - run a program \section command command - run a program
\subsection command-synopsis Synopsis \subsection command-synopsis Synopsis
\fish{synopsis} <tt>command COMMANDNAME [OPTIONS...]</tt>
command [OPTIONS] COMMANDNAME [ARGS...]
\endfish
\subsection command-description Description \subsection command-description Description
`command` forces the shell to execute the program `COMMANDNAME` and ignore any functions or builtins with the same name. \c command forces the shell to execute the program \c COMMANDNAME and ignore any functions or builtins with the same name.
The following options are available: \subsection command-example Example
- `-s` or `--search` returns the name of the disk file that would be executed, or nothing if no file with the specified name could be found in the `$PATH`. <tt>command ls</tt> causes fish to execute the \c ls program, even if an 'ls' function exists.
With the `-s` option, `command` treats every argument as a separate command to look up and sets the exit status to 0 if any of the specified commands were found, or 1 if no commands could be found.
For basic compatibility with POSIX `command`, the `-v` flag is recognized as an alias for `-s`.
\subsection command-example Examples
`command ls` causes fish to execute the `ls` program, even if an `ls` function exists.
`command -s ls` returns the path to the `ls` program.

View File

@@ -1,80 +1,63 @@
\section commandline commandline - set or get the current command line buffer \section commandline commandline - set or get the current command line buffer
\subsection commandline-synopsis Synopsis \subsection commandline-synopsis Synopsis
\fish{synopsis} <tt>commandline [OPTIONS] [CMD]</tt>
commandline [OPTIONS] [CMD]
\endfish
\subsection commandline-description Description \subsection commandline-description Description
`commandline` can be used to set or get the current contents of the command line buffer. \c commandline can be used to set or get the current contents of the command
line buffer.
With no parameters, `commandline` returns the current value of the command line. With no parameters, \c commandline returns the current value of the command
line.
With `CMD` specified, the command line buffer is erased and replaced with the contents of `CMD`. With \c CMD specified, the command line buffer is erased and replaced with
the contents of \c CMD.
The following options are available: The following options are available:
- `-C` or `--cursor` set or get the current cursor position, not the contents of the buffer. If no argument is given, the current cursor position is printed, otherwise the argument is interpreted as the new cursor position. - \c -C or \c --cursor set or get the current cursor position, not
the contents of the buffer. If no argument is given, the current
cursor position is printed, otherwise the argument is interpreted
as the new cursor position.
- \c -f or \c --function inject readline functions into the
reader. This option cannot be combined with any other option. It
will cause any additional arguments to be interpreted as readline
functions, and these functions will be injected into the reader, so
that they will be returned to the reader before any additional
actual key presses are read.
- `-f` or `--function` inject readline functions into the reader. This option cannot be combined with any other option. It will cause any additional arguments to be interpreted as readline functions, and these functions will be injected into the reader, so that they will be returned to the reader before any additional actual key presses are read. The following options change the way \c commandline updates the
command line buffer:
The following options change the way `commandline` updates the command line buffer: - \c -a or \c --append do not remove the current commandline, append
the specified string at the end of it
- \c -i or \c --insert do not remove the current commandline, insert
the specified string at the current cursor position
- \c -r or \c --replace remove the current commandline and replace it
with the specified string (default)
- `-a` or `--append` do not remove the current commandline, append the specified string at the end of it The following options change what part of the commandline is printed
or updated:
- `-i` or `--insert` do not remove the current commandline, insert the specified string at the current cursor position - \c -b or \c --current-buffer select the entire buffer (default)
- \c -j or \c --current-job select the current job
- \c -p or \c --current-process select the current process
- \c -t or \c --current-token select the current token.
- `-r` or `--replace` remove the current commandline and replace it with the specified string (default) The following options change the way \c commandline prints the current
commandline buffer:
The following options change what part of the commandline is printed or updated: - \c -c or \c --cut-at-cursor only print selection up until the
current cursor position
- \c -o or \c --tokenize tokenize the selection and print one string-type token per line
- `-b` or `--current-buffer` select the entire buffer (default)
- `-j` or `--current-job` select the current job
- `-p` or `--current-process` select the current process
- `-t` or `--current-token` select the current token.
The following options change the way `commandline` prints the current commandline buffer:
- `-c` or `--cut-at-cursor` only print selection up until the current cursor position
- `-o` or `--tokenize` tokenize the selection and print one string-type token per line
If `commandline` is called during a call to complete a given string using `complete -C STRING`, `commandline` will consider the specified string to be the current contents of the command line.
The following options output metadata about the commandline state:
- `-L` or `--line` print the line that the cursor is on, with the topmost line starting at 1
- `-S` or `--search-mode` evaluates to true if the commandline is performing a history search
- `-P` or `--paging-mode` evaluates to true if the commandline is showing pager contents, such as tab completions
If \c commandline is called during a call to complete a given string
using <code>complete -C STRING</code>, \c commandline will consider the
specified string to be the current contents of the command line.
\subsection commandline-example Example \subsection commandline-example Example
`commandline -j $history[3]` replaces the job under the cursor with the third item from the command line history. <tt>commandline -j $history[3]</tt> replaces the job under the cursor with the
third item from the command line history.
If the commandline contains
\fish
>_ echo $fl___ounder >&2 | less; and echo $catfish
\endfish
(with the cursor on the "o" of "flounder")
Then the following invocations behave like this:
\fish
>_ commandline -t
$flounder
>_ commandline -ct
$fl
>_ commandline -b # or just commandline
echo $flounder >&2 | less; and echo $catfish
>_ commandline -p
echo $flounder >&2
>_ commandline -j
echo $flounder >&2 | less
\endfish

View File

@@ -1,38 +1,6 @@
/** /** \page commands Commands, functions and builtins bundled with fish
\page commands Commands Fish ships with a large number of builtin commands, shellscript functions and external commands. These are all described below.
\htmlonly[block]
<div class="fish_left_bar">
<div class="logo"></div>
<div class="menu commands_menu">
\endhtmlonly
@command_list_toc@
\htmlonly[block]
</div>
</div>
<div class="commands fish_right_bar">
<h1 class="interior_title">Command reference</h1>
\endhtmlonly
`fish` ships with a large number of builtin commands, shellscript functions and external commands. These are all described below.
Almost all fish commands respond to the `-h` or `--help` options to display their relevant help, also accessible using the `help` and `man` commands, like so:
\fish
echo -h
echo --help
# Prints help to the terminal window
man echo
# Displays the man page in the system pager
# (normally 'less', 'more' or 'most').
help echo
# Open a web browser to show the relevant documentation
\endfish
@command_list@ @command_list@
\htmlonly[block]
</div>
\endhtmlonly
*/ */

View File

@@ -1,21 +1,7 @@
\section complete complete - edit command specific tab-completions \section complete complete - edit command specific tab-completions
\subsection complete-synopsis Synopsis \subsection complete-synopsis Synopsis
\fish{synopsis} <tt>complete (-c|--command|-p|--path) COMMAND [(-s|--short-option) SHORT_OPTION] [(-l|--long-option|-o|--old-option) LONG_OPTION [(-a||--arguments) OPTION_ARGUMENTS] [(-d|--description) DESCRIPTION] </tt>
complete ( -c | --command | -p | --path ) COMMAND
[( -c | --command | -p | --path ) COMMAND]...
[( -e | --erase )]
[( -s | --short-option ) SHORT_OPTION]...
[( -l | --long-option | -o | --old-option ) LONG_OPTION]...
[( -a | --arguments ) OPTION_ARGUMENTS]
[( -f | --no-files )]
[( -r | --require-parameter )]
[( -x | --exclusive )]
[( -w | --wraps ) WRAPPED_COMMAND]...
[( -n | --condition ) CONDITION]
[( -d | --description ) DESCRIPTION]
complete ( -C[STRING] | --do-complete[=STRING] )
\endfish
\subsection complete-description Description \subsection complete-description Description
@@ -23,102 +9,69 @@ For an introduction to specifying completions, see <a
href='index.html#completion-own'>Writing your own completions</a> in href='index.html#completion-own'>Writing your own completions</a> in
the fish manual. the fish manual.
- `COMMAND` is the name of the command for which to add a completion. - <tt>COMMAND</tt> is the name of the command for which to add a completion
- <tt>SHORT_OPTION</tt> is a one character option for the command
- <tt>LONG_OPTION</tt> is a multi character option for the command
- <tt>OPTION_ARGUMENTS</tt> is parameter containing a space-separated list of possible option-arguments, which may contain subshells
- <tt>DESCRIPTION</tt> is a description of what the option and/or option arguments do
- <tt>-C STRING</tt> or <tt>--do-complete=STRING</tt> makes complete try to find all possible completions for the specified string
- <tt>-e</tt> or <tt>--erase</tt> implies that the specified completion should be deleted
- <tt>-f</tt> or <tt>--no-files</tt> specifies that the option specified by this completion may not be followed by a filename
- <tt>-n</tt> or <tt>--condition</tt> specifies a shell command that must return 0 if the completion is to be used. This makes it possible to specify completions that should only be used in some cases.
- <tt>-o</tt> or <tt>--old-option</tt> implies that the command uses old long style options with only one dash
- <tt>-p</tt> or <tt>--path</tt> implies that the string COMMAND is the full path of the command
- <tt>-r</tt> or <tt>--require-parameter</tt> specifies that the option specified by this completion always must have an option argument, i.e. may not be followed by another option
- <tt>-u</tt> or <tt>--unauthoritative</tt> implies that there may be more options than the ones specified, and that fish should not assume that options not listed are spelling errors
- <tt>-A</tt> or <tt>--authoritative</tt> implies that there may be no more options than the ones specified, and that fish should assume that options not listed are spelling errors
- <tt>-x</tt> or <tt>--exclusive</tt> implies both <tt>-r</tt> and <tt>-f</tt>
- `SHORT_OPTION` is a one character option for the command. Command specific tab-completions in \c fish are based on the notion
of options and arguments. An option is a parameter which begins with a
hyphen, such as '-h', '-help' or '--help'. Arguments are parameters
that do not begin with a hyphen. Fish recognizes three styles of
options, the same styles as the GNU version of the getopt
library. These styles are:
- `LONG_OPTION` is a multi character option for the command. - Short options, like '-a'. Short options are a single character long, are preceded by a single hyphen and may be grouped together (like '-la', which is equivalent to '-l -a'). Option arguments may be specified in the following parameter ('-w 32') or by appending the option with the value ('-w32').
- Old style long options, like '-Wall'. Old style long options can be more than one character long, are preceded by a single hyphen and may not be grouped together. Option arguments are specified in the following parameter ('-ao null').
- GNU style long options, like '--colors'. GNU style long options can be more than one character long, are preceded by two hyphens, and may not be grouped together. Option arguments may be specified in the following parameter ('--quoting-style shell') or by appending the option with a '=' and the value ('--quoting-style=shell'). GNU style long options may be abbreviated so long as the abbreviation is unique ('--h' is equivalent to '--help' if help is the only long option beginning with an 'h').
- `OPTION_ARGUMENTS` is parameter containing a space-separated list of possible option-arguments, which may contain command substitutions. The options for specifying command name, command path, or command
switches may all be used multiple times to specify multiple commands
- `DESCRIPTION` is a description of what the option and/or option arguments do. which have the same completion or multiple switches accepted by a
command.
- `-c COMMAND` or `--command COMMAND` specifies that `COMMAND` is the name of the command.
- `-p COMMAND` or `--path COMMAND` specifies that `COMMAND` is the absolute path of the program (optionally containing wildcards).
- `-e` or `--erase` deletes the specified completion.
- `-s SHORT_OPTION` or `--short-option=SHORT_OPTION` adds a short option to the completions list.
- `-l LONG_OPTION` or `--long-option=LONG_OPTION` adds a GNU style long option to the completions list.
- `-o LONG_OPTION` or `--old-option=LONG_OPTION` adds an old style long option to the completions list (See below for details).
- `-a OPTION_ARGUMENTS` or `--arguments=OPTION_ARGUMENTS` adds the specified option arguments to the completions list.
- `-f` or `--no-files` specifies that the options specified by this completion may not be followed by a filename.
- `-r` or `--require-parameter` specifies that the options specified by this completion always must have an option argument, i.e. may not be followed by another option.
- `-x` or `--exclusive` implies both `-r` and `-f`.
- `-w WRAPPED_COMMAND` or `--wraps=WRAPPED_COMMAND` causes the specified command to inherit completions from the wrapped command (See blow for details).
- `-n` or `--condition` specifies a shell command that must return 0 if the completion is to be used. This makes it possible to specify completions that should only be used in some cases.
- `-CSTRING` or `--do-complete=STRING` makes complete try to find all possible completions for the specified string.
- `-C` or `--do-complete` with no argument makes complete try to find all possible completions for the current command line buffer. If the shell is not in interactive mode, an error is returned.
Command specific tab-completions in `fish` are based on the notion of options and arguments. An option is a parameter which begins with a hyphen, such as '`-h`', '`-help`' or '`--help`'. Arguments are parameters that do not begin with a hyphen. Fish recognizes three styles of options, the same styles as the GNU version of the getopt library. These styles are:
- Short options, like '`-a`'. Short options are a single character long, are preceded by a single hyphen and may be grouped together (like '`-la`', which is equivalent to '`-l -a`'). Option arguments may be specified in the following parameter ('`-w 32`') or by appending the option with the value ('`-w32`').
- Old style long options, like '`-Wall`'. Old style long options can be more than one character long, are preceded by a single hyphen and may not be grouped together. Option arguments are specified in the following parameter ('`-ao null`').
- GNU style long options, like '`--colors`'. GNU style long options can be more than one character long, are preceded by two hyphens, and may not be grouped together. Option arguments may be specified in the following parameter ('`--quoting-style shell`') or by appending the option with a '`=`' and the value ('`--quoting-style=shell`'). GNU style long options may be abbreviated so long as the abbreviation is unique ('`--h`') is equivalent to '`--help`' if help is the only long option beginning with an 'h').
The options for specifying command name and command path may be used multiple times to define the same completions for multiple commands.
The options for specifying command switches and wrapped commands may be used multiple times to define multiple completions for the command(s) in a single call.
Invoking `complete` multiple times for the same command adds the new definitions on top of any existing completions defined for the command.
When `-a` or `--arguments` is specified in conjunction with long, short, or old style options, the specified arguments are only used as completions when attempting to complete an argument for any of the specified options. If `-a` or `--arguments` is specified without any long, short, or old style options, the specified arguments are used when completing any argument to the command (except when completing an option argument that was specified with `-r` or `--require-parameter`).
Command substitutions found in `OPTION_ARGUMENTS` are not expected to return a space-separated list of arguments. Instead they must return a newline-separated list of arguments, and each argument may optionally have a tab character followed by the argument description. Any description provided in this way overrides a description given with `-d` or `--description`.
The `-w` or `--wraps` options causes the specified command to inherit completions from another command. The inheriting command is said to "wrap" the inherited command. The wrapping command may have its own completions in addition to inherited ones. A command may wrap multiple commands, and wrapping is transitive: if A wraps B, and B wraps C, then A automatically inherits all of C's completions. Wrapping can be removed using the `-e` or `--erase` options. Note that wrapping only works for completions specified with `-c` or `--command` and are ignored when specifying completions with `-p` or `--path`.
When erasing completions, it is possible to either erase all completions for a specific command by specifying `complete -c COMMAND -e`, or by specifying a specific completion option to delete by specifying either a long, short or old style option.
When erasing completions, it is possible to either erase all
completions for a specific command by specifying <tt>complete -e -c
COMMAND</tt>, or by specifying a specific completion option to delete
by specifying either a long, short or old style option.
\subsection complete-example Example \subsection complete-example Example
The short style option `-o` for the `gcc` command requires that a file follows it. This can be done using writing: The short style option <tt>-o</tt> for the \c gcc command requires
that a file follows it. This can be done using writing <tt>complete
-c gcc -s o -r</tt>.
\fish The short style option <tt>-d</tt> for the \c grep command requires
complete -c gcc -s o -r that one of the strings 'read', 'skip' or 'recurse' is used. This can
\endfish be specified writing <tt>complete -c grep -s d -x -a "read skip
recurse"</tt>.
The short style option `-d` for the `grep` command requires that one of the strings '`read`', '`skip`' or '`recurse`' is used. This can be specified writing: The \c su command takes any username as an argument. Usernames are
given as the first colon-separated field in the file /etc/passwd. This
can be specified as: <tt>complete -x -c su -d "Username" -a "(cat
/etc/passwd|cut -d : -f 1)" </tt>.
\fish The \c rpm command has several different modes. If the \c -e or \c
complete -c grep -s d -x -a "read skip recurse" --erase flag has been specified, \c rpm should delete one or more
\endfish packages, in which case several switches related to deleting packages
are valid, like the \c nodeps switch.
The `su` command takes any username as an argument. Usernames are given as the first colon-separated field in the file /etc/passwd. This can be specified as:
\fish
complete -x -c su -d "Username" -a "(cat /etc/passwd | cut -d : -f 1)"
\endfish
The `rpm` command has several different modes. If the `-e` or `--erase` flag has been specified, `rpm` should delete one or more packages, in which case several switches related to deleting packages are valid, like the `nodeps` switch.
This can be written as: This can be written as:
\fish <tt>complete -c rpm -n "__fish_contains_opt -s e erase" -l nodeps -d
complete -c rpm -n "__fish_contains_opt -s e erase" -l nodeps -d "Don't check dependencies" "Don't check dependencies"</tt>
\endfish
where `__fish_contains_opt` is a function that checks the command line buffer for the presence of a specified set of options. where \c __fish_contains_opt is a function that checks the commandline
buffer for the presence of a specified set of options.
To implement an alias, use the `-w` or `--wraps` option:
\fish
complete -c hub -w git
\endfish
Now hub inherits all of the completions from git. Note this can also be specified in a function declaration.

View File

@@ -1,38 +1,26 @@
\section contains contains - test if a word is present in a list \section contains contains - test if a word is present in a list
\subsection contains-synopsis Synopsis \subsection contains-synopsis Synopsis
\fish{synopsis} <code>contains [OPTIONS] KEY [VALUES...]</code>
contains [OPTIONS] KEY [VALUES...]
\endfish
\subsection contains-description Description \subsection contains-description Description
`contains` tests whether the set `VALUES` contains the string `KEY`. If so, `contains` exits with status 0; if not, it exits with status 1. \c contains tests whether the set \c VALUES contains the string
<code>KEY</code>. If so, \c contains exits with status 0; if not, it exits
with status 1.
The following options are available: The following options are available:
- `-i` or `--index` print the word index - \c -i or \c --index print the word index
- \c -h or \c --help display this message
Note that, like GNU tools, `contains` interprets all arguments starting with a `-` as options to contains, until it reaches an argument that is `--` (two dashes). See the examples below.
\subsection contains-example Example \subsection contains-example Example
<pre>
\fish
for i in ~/bin /usr/local/bin for i in ~/bin /usr/local/bin
if not contains $i $PATH if not contains \$i \$PATH
set PATH $PATH $i set PATH \$PATH \$i
end end
end end
\endfish </pre>
The above code tests if `~/bin` and `/usr/local/bin` are in the path and adds them if not. The above code tests if \c ~/bin and \c /usr/local/bin are in the path and adds them if not.
\fish
function hasargs
if contains -- -q $argv
echo '$argv contains a -q option'
end
end
\endfish
The above code checks for `-q` in the argument list, using the `--` argument to demarcate options to `contains` from the key to search for.

View File

@@ -1,23 +1,19 @@
\section continue continue - skip the remainder of the current iteration of the current inner loop \section continue continue - skip the remainder of the current iteration of the current inner loop
\subsection continue-synopsis Synopsis \subsection continue-synopsis Synopsis
\fish{synopsis} <tt>LOOP_CONSTRUCT; [COMMANDS...;] continue; [COMMANDS...;] end</tt>
LOOP_CONSTRUCT; [COMMANDS...;] continue; [COMMANDS...;] end
\endfish
\subsection continue-description Description \subsection continue-description Description
\c continue skips the remainder of the current iteration of the current inner loop, such as a <a href="#for">for</a> loop or a <a href="#while">while</a> loop. It is usually added inside of a conditional block such as an <a href="#if">if</a> statement or a <a href="#switch">switch</a> statement.
`continue` skips the remainder of the current iteration of the current inner loop, such as a <a href="#for">for</a> loop or a <a href="#while">while</a> loop. It is usually added inside of a conditional block such as an <a href="#if">if</a> statement or a <a href="#switch">switch</a> statement.
\subsection continue-example Example \subsection continue-example Example
The following code removes all tmp files that do not contain the word smurf. The following code removes all tmp files that do not contain the word smurf.
\fish <pre>
for i in *.tmp for i in *.tmp
if grep smurf $i if grep smurf $i
continue continue
end end
rm $i rm $i
end end
\endfish </pre>

View File

@@ -1,25 +1,29 @@
\section count count - count the number of elements of an array \section count count - count the number of elements of an array
\subsection count-synopsis Synopsis \subsection count-synopsis Synopsis
\fish{synopsis} <tt>count $VARIABLE</tt>
count $VARIABLE
\endfish
\subsection count-description Description \subsection count-description Description
`count` prints the number of arguments that were passed to it. This is usually used to find out how many elements an environment variable array contains. <tt>count</tt> prints the number of arguments that were
passed to it. This is usually used to find out how many elements an
environment variable array contains.
`count` does not accept any options, including `-h` or `--help`. \c count does not accept any options, including '-h'.
`count` exits with a non-zero exit status if no arguments were passed to it, and with zero if at least one argument was passed.
\c count exits with a non-zero exit status if no arguments were passed
to it, and with zero if at least one argument was passed.
\subsection count-example Example \subsection count-example Example
\fish <pre>
count $PATH count $PATH
# Returns the number of directories in the users PATH variable. </pre>
returns the number of directories in the users PATH variable.
<pre>
count *.txt count *.txt
# Returns the number of files in the current working directory ending with the suffix '.txt'. </pre>
\endfish
returns the number of files in the current working directory ending with the suffix '.txt'.

View File

@@ -1,110 +1,134 @@
/** /** \page design Design document
\page design Design document
\htmlonly[block]
<div class="fish_only_bar">
<div class="design">
<h1 class="interior_title">Design documentation</h1>
\endhtmlonly
\section design-overview Overview \section design-overview Overview
This is a description of the design principles that have been used to design fish. The fish design has three high level goals. These are: This is a description of the design principles that have been used to
design fish. The fish design has three high level goals. These are:
-# Everything that can be done in other shell languages should be possible to do in fish, though fish may rely on external commands in doing so. -# Everything that can be done in other shell languages should be
possible to do in fish, though fish may rely on external commands in
-# Fish should be user friendly, but not at the expense of expressiveness. Most tradeoffs between power and ease of use can be avoided with careful design. doing so.
-# Fish should be user friendly, but not at the expense of expressiveness.
-# Whenever possible without breaking the above goals, fish should follow the Posix syntax. Most tradeoffs between power and ease of use can be avoided with careful design.
-# Whenever possible without breaking the above goals, fish should
To achieve these high-level goals, the fish design relies on a number of more specific design principles. These are presented below, together with a rationale and a few examples for each. follow the Posix syntax.
To achieve these high-level goals, the fish design relies on a number
of more specific design principles. These are presented below,
together with a rationale and a few examples for each.
\section ortho The law of orthogonality \section ortho The law of orthogonality
The shell language should have a small set of orthogonal features. Any situation where two features are related but not identical, one of them should be removed, and the other should be made powerful and general enough to handle all common use cases of either feature. The shell language should have a small set of orthogonal features. Any
situation where two features are related but not identical, one of them
should be removed, and the other should be made powerful and general
enough to handle all common use cases of either feature.
Rationale: Rationale:
Related features make the language larger, which makes it harder to learn. It also increases the size of the source code, making the program harder to maintain and update. Related features make the language larger, which makes it harder to
learn. It also increases the size of the sourcecode, making the
program harder to maintain and update.
Examples: Examples:
- Here documents are too similar to using echo inside of a pipeline. - Here documents are too similar to using echo inside of a pipeline.
- Subshells, command substitution and process substitution are strongly related. \c fish only supports command substitution, the others can be achieved either using a block or the psub shellscript function.
- Having both aliases and functions is confusing, especially since both of them have limitations and problems. \c fish functions have none of the drawbacks of either syntax.
- The many Posix quoting styles are silly, especially \$''.
- Subshells, command substitution and process substitution are strongly related. `fish` only supports command substitution, the others can be achieved either using a block or the psub shellscript function. \section sep The law of responsiveness
- Having both aliases and functions is confusing, especially since both of them have limitations and problems. `fish` functions have none of the drawbacks of either syntax.
- The many Posix quoting styles are silly, especially $''.
\section design-response The law of responsiveness
The shell should attempt to remain responsive to the user at all times, even in the face of contended or unresponsive filesystems. It is only acceptable to block in response to a user initiated action, such as running a command. The shell should attempt to remain responsive to the user at all times, even in the face of contended or unresponsive filesystems. It is only acceptable to block in response to a user initiated action, such as running a command.
Rationale: Rationale:
Bad performance increases user-facing complexity, because it trains users to recognize and route around slow use cases. It is also incredibly frustrating. Bad performance increases user-facing complexity, because it trains users to recognize and route around slow use cases. It is also incredibly frustrating.
Examples: Examples:
- Features like syntax highlighting and autosuggestions must perform all of their disk I/O asynchronously. - Features like syntax highlighting and autosuggestions must perform all of their disk I/O asynchronously.
- Startup should minimize forks and disk I/O, so that fish can be started even if the system is under load. - Startup should minimize forks and disk I/O, so that fish can be started even if the system is under load.
\section design-configurability Configurability is the root of all evil \section conf Configurability is the root of all evil
Every configuration option in a program is a place where the program is too stupid to figure out for itself what the user really wants, and should be considered a failure of both the program and the programmer who implemented it. Every configuration option in a program is a place where the program
is too stupid to figure out for itself what the user really wants, and
should be considered a failiure of both the program and the programmer
who implemented it.
Rationale: Rationale:
Different configuration options are a nightmare to maintain, since the number of potential bugs caused by specific configuration combinations quickly becomes an issue. Configuration options often imply assumptions about the code which change when reimplementing the code, causing issues with backwards compatibility. But mostly, configuration options should be avoided since they simply should not exist, as the program should be smart enough to do what is best, or at least a good enough approximation of it.
Different configuration options are a nightmare to maintain, since the
number of potential bugs caused by specific configuration combinations
quickly becomes an issue. Configuration options often imply
assumptions about the code which change when reimplementing the code,
causing issues with backwards compatibility. But mostly, configuration
options should be avoided since they simply should not exist, as the
program should be smart enough to do what is best, or at least a good
enough approximation of it.
Examples: Examples:
- Fish allows the user to set various syntax highlighting colors. This is needed because fish does not know what colors the terminal uses by default, which might make some things unreadable. The proper solution would be for text color preferences to be defined centrally by the user for all programs, and for the terminal emulator to send these color properties to fish. - Fish allows the user to set various syntax highlighting colors. This is needed because fish does not know what colors the terminal uses by default, which might make some things unreadable. The proper solution would be for text color preferences to be defined centrally by the user for all programs, and for the terminal emulator to send these color properties to fish.
- Fish does not allow you to set the history filename, the number of history entries, different language substyles or any number of other common shell configuration options. - Fish does not allow you to set the history filename, the number of history entries, different language substyles or any number of other common shell configuration options.
A special note on the evils of configurability is the long list of very useful features found in some shells, that are not turned on by default. Both zsh and bash support command-specific completions, but no such completions are shipped with bash by default, and they are turned off by default in zsh. Other features that zsh supports that are disabled by default include tab-completion of strings containing wildcards, a sane completion pager and a history file. A special note on the evils of configurability is the long list of
very useful features found in some shells, that are not turned on by
default. Both zsh and bash support command specific completions, but
no such completions are shipped with bash by default, and they are
turned off by default in zsh. Other features that zsh support that are
disabled by default include tab-completion of strings containing
wildcards, a sane completion pager and a history file.
\section user The law of user focus \section user The law of user focus
When designing a program, one should first think about how to make a intuitive and powerful program. Implementation issues should only be considered once a user interface has been designed. When designing a program, one should first think about how to make a
intuitive and powerful program. Implementation issues should only be
considered once a user interface has been designed.
Rationale: Rationale:
This design rule is different than the others, since it describes how one should go about designing new features, not what the features should be. The problem with focusing on what can be done, and what is easy to do, is that too much of the implementation is exposed. This means that the user must know a great deal about the underlying system to be able to guess how the shell works, it also means that the language will often be rather low-level. This design rule is different than the others, since it describes how
one should go about designing new features, not what the features
should be. The problem with focusing on what can be done, and what is
easy to do, is that to much of the implementation is exposed. This
means that the user must know a great deal about the underlying system
to be able to guess how the shell works, it also means that the
language will often be rather low-level.
Examples: Examples:
- There should only be one type of input to the shell, lists of commands. Loops, conditionals and variable assignments are all performed through regular commands. - There should only be one type of input to the shell, lists of commands. Loops, conditionals and variable assignments are all performed through regular commands.
- The differences between builtin commands, shellscript functions and builtin commands should be made as small as possible. Builtins and shellscript functions should have exactly the same types of argument expansion as other commands, should be possible to use in any position in a pipeline, and should support any io redirection.
- The differences between built-in commands and shellscript functions should be made as small as possible. Built-ins and shellscript functions should have exactly the same types of argument expansion as other commands, should be possible to use in any position in a pipeline, and should support any I/O redirection.
- Instead of forking when performing command substitution to provide a fake variable scope, all fish commands are performed from the same process, and fish instead supports true scoping. - Instead of forking when performing command substitution to provide a fake variable scope, all fish commands are performed from the same process, and fish instead supports true scoping.
- All blocks end with the \c end builtin.
- All blocks end with the `end` built-in.
\section disc The law of discoverability \section disc The law of discoverability
A program should be designed to make its features as easy as possible to discover for the user. A program should be designed to make its features as
easy as possible to discover for the user.
Rationale: Rationale:
A program whose features are discoverable turns a new user into an expert in a shorter span of time, since the user will become an expert on the program simply by using it.
The main benefit of a graphical program over a command-line-based program is discoverability. In a graphical program, one can discover all the common features by simply looking at the user interface and guessing what the different buttons, menus and other widgets do. The traditional way to discover features in command-line programs is through manual pages. This requires both that the user starts to use a different program, and then they remember the new information until the next time they use the same program. A program whose features are discoverable turns a new user into an
expert in a shorter span of time, since the user will become an expert
on the program simply by using it.
The main benefit of a graphical program over a command line-based
program is discoverability. In a graphical program, one can discover
all the common features by simply looking at the user interface and
guessing what the different buttons, menus and other widgets do. The
traditional way to discover features in commandline programs is
through manual pages. This requires both that the user starts to use a
different program, and the she/he then remembers the new information
until the next time she/he uses the same program.
Examples: Examples:
- Everything should be tab-completable, and every tab completion should have a description. - Everything should be tab-completable, and every tab completion should have a description.
- Every syntax error and error in a builtin command should contain an error message describing what went wrong and a relevant help page. Whenever possible, errors should be flagged red by the syntax highlighter.
- Every syntax error and error in a built-in command should contain an error message describing what went wrong and a relevant help page. Whenever possible, errors should be flagged red by the syntax highlighter.
- The help manual should be easy to read, easily available from the shell, complete and contain many examples - The help manual should be easy to read, easily available from the shell, complete and contain many examples
- The language should be uniform, so that once the user understands the command/argument syntax, he will know the whole language, and be able to use tab-completion to discover new featues.
- The language should be uniform, so that once the user understands the command/argument syntax, they will know the whole language, and be able to use tab-completion to discover new features.
\htmlonly[block]
</div>
</div>
\endhtmlonly
*/ */

View File

@@ -1,14 +1,12 @@
\section dirh dirh - print directory history \section dirh dirh - print directory history
\subsection dirh-synopsis Synopsis \subsection dirh-synopsis Synopsis
\fish{synopsis} <tt>dirh</tt>
dirh
\endfish
\subsection dirh-description Description \subsection dirh-description Description
`dirh` prints the current directory history. The current position in the history is highlighted using the color defined in the `fish_color_history_current` environment variable. <tt>dirh</tt> prints the current directory history. The current position in the
history is highlighted using the color defined in the
<tt>fish_color_history_current</tt> environment variable.
`dirh` does not accept any parameters. \c dirh does not accept any parameters.
Note that the `cd` command limits directory history to the 25 most recently visited directories. The history is stored in the `$dirprev` and `$dirnext` variables.

View File

@@ -1,15 +1,10 @@
\section dirs dirs - print directory stack \section dirs dirs - print directory stack
\subsection dirs-synopsis Synopsis \subsection dirs-synopsis Synopsis
\fish{synopsis} <tt>dirs</tt>
dirs
dirs -c
\endfish
\subsection dirs-description Description \subsection dirs-description Description
<tt>dirs</tt> prints the current directory stack, as created by the
<code><a href="#pushd">pushd</a></code> command.
`dirs` prints the current directory stack, as created by the <a href="#pushd">`pushd`</a> command. \c dirs does not accept any parameters.
With "-c", it clears the directory stack instead.
`dirs` does not accept any parameters.

View File

@@ -1,60 +1,39 @@
\section echo echo - display a line of text \section echo echo - display a line of text
\subsection echo-synopsis Synopsis \subsection echo-synopsis Synopsis
\fish{synopsis} <tt>echo [STRING]</tt>
echo [OPTIONS] [STRING]
\endfish
\subsection echo-description Description \subsection echo-description Description
`echo` displays a string of text. \c echo displays a string of text.
The following options are available: The following options are available:
- `-n`, Do not output a newline - \c -n, \c Do not output a newline
- \c -s, \c Do not separate arguments with spaces
- `-s`, Do not separate arguments with spaces - \c -E, \c Disable interpretation of backslash escapes (default)
- \c -e, \c Enable interpretation of backslash escapes
- `-E`, Disable interpretation of backslash escapes (default) - \c -h, \c --help Display this help
- `-e`, Enable interpretation of backslash escapes
\subsection echo-escapes Escape Sequences \subsection echo-escapes Escape Sequences
If `-e` is used, the following sequences are recognized: If \c -e is used, the following sequences are recognized:
- `\` backslash - \c \\\\ \c backslash
- \\a alert (BEL)
- `\a` alert (BEL) - \\b backspace
- \\c produce no further output
- `\b` backspace - \\e escape
- \\f form feed
- `\c` produce no further output - \\n new line
- \\r carriage return
- `\e` escape - \\t horizontal tab
- \\v vertical tab
- `\f` form feed - \\0NNN byte with octal value NNN (1 to 3 digits)
- \\xHH byte with hexadecimal value HH (1 to 2 digits)
- `\n` new line
- `\r` carriage return
- `\t` horizontal tab
- `\v` vertical tab
- `\0NNN` byte with octal value NNN (1 to 3 digits)
- `\xHH` byte with hexadecimal value HH (1 to 2 digits)
\subsection echo-example Example \subsection echo-example Example
\fish <tt>echo 'Hello World'</tt> Print hello world to stdout
echo 'Hello World'
\endfish
Print hello world to stdout
\fish <tt>echo -e 'Top\\nBottom'</tt> Print Top and Bottom on separate lines, using an escape sequence
echo -e 'Top\nBottom'
\endfish
Print Top and Bottom on separate lines, using an escape sequence

View File

@@ -1,23 +1,21 @@
\section else else - execute command if a condition is not met \section else else - execute command if a condition is not met
\subsection else-synopsis Synopsis \subsection else-synopsis Synopsis
\fish{synopsis} <tt>if CONDITION; COMMANDS_TRUE...; [else; COMMANDS_FALSE...;] end</tt>
if CONDITION; COMMANDS_TRUE...; [else; COMMANDS_FALSE...;] end
\endfish
\subsection else-description Description \subsection else-description Description
<tt>if</tt> will execute the command \c CONDITION. If the condition's exit
`if` will execute the command `CONDITION`. If the condition's exit status is 0, the commands `COMMANDS_TRUE` will execute. If it is not 0 and `else` is given, `COMMANDS_FALSE` will be executed. status is 0, the commands \c COMMANDS_TRUE will execute. If it is not 0 and
<tt>else</tt> is given, \c COMMANDS_FALSE will be executed.
\subsection else-example Example \subsection else-example Example
The following code tests whether a file `foo.txt` exists as a regular file. The following code tests whether a file \c foo.txt exists as a regular file.
\fish <pre>
if test -f foo.txt if test -f foo.txt
echo foo.txt exists echo foo.txt exists
else else
echo foo.txt does not exist echo foo.txt does not exist
end end
\endfish </pre>

View File

@@ -1,23 +1,20 @@
\section emit emit - Emit a generic event \section emit emit - Emit a generic event
\subsection emit-synopsis Synopsis \subsection block-synopsis Synopsis
\fish{synopsis} <tt>emit EVENT_NAME [ARGUMENTS...]</tt>
emit EVENT_NAME [ARGUMENTS...]
\endfish
\subsection emit-description Description \subsection emit-description Description
`emit` emits, or fires, an event. Events are delivered to, or caught by, special functions called event handlers. The arguments are passed to the event handlers as function arguments. \c emit emits, or fires, an event. Events are delivered to, or caught by, special functions called event handlers. The arguments are passed to the event handlers as function arguments.
\subsection emit-example Example \subsection emit-example Example
The following code first defines an event handler for the generic event named 'test_event', and then emits an event of that type. The following code first defines an event handler for the generic
event named 'test_event', and then emits an event of that type.
\fish <pre>function event_test --on-event test_event
function event_test --on-event test_event
echo event test: $argv echo event test: $argv
end end
emit test_event something emit test_event something
\endfish </pre>

View File

@@ -1,19 +1,19 @@
\section end end - end a block of commands. \section end end - end a block of commands.
\subsection end-synopsis Synopsis \subsection end-synopsis Synopsis
\fish{synopsis} <pre>
begin; [COMMANDS...] end begin; [COMMANDS...] end
if CONDITION; COMMANDS_TRUE...; [else; COMMANDS_FALSE...;] end if CONDITION; COMMANDS_TRUE...; [else; COMMANDS_FALSE...;] end
while CONDITION; COMMANDS...; end while CONDITION; COMMANDS...; end
for VARNAME in [VALUES...]; COMMANDS...; end for VARNAME in [VALUES...]; COMMANDS...; end
switch VALUE; [case [WILDCARD...]; [COMMANDS...]; ...] end switch VALUE; [case [WILDCARD...]; [COMMANDS...]; ...] end
\endfish </pre>
\subsection end-description Description \subsection end-description Description
<tt>end</tt> ends a block of commands.
`end` ends a block of commands.
For more information, read the For more information, read the
documentation for the block constructs, such as `if`, `for` and `while`. documentation for the block constructs, such as \c if, \c for and \c
while.
The `end` command does not change the current exit status. The \c end command does not change the current exit status.

View File

@@ -1,20 +1,19 @@
\section eval eval - evaluate the specified commands \section eval eval - evaluate the specified commands
\subsection eval-synopsis Synopsis \subsection eval-synopsis Synopsis
\fish{synopsis} <tt>eval [COMMANDS...]</tt>
eval [COMMANDS...]
\endfish
\subsection eval-description Description \subsection eval-description Description
`eval` evaluates the specified parameters as a command. If more than one parameter is specified, all parameters will be joined using a space character as a separator. <tt>eval</tt> evaluates the specified parameters as a command. If more than one parameter is specified, all parameters will be joined using a space character as a separator.
\subsection eval-example Example \subsection eval-example Example
The following code will call the ls command. Note that `fish` does not support the use of shell variables as direct commands; `eval` can be used to work around this. The folloing code will call the ls command. Note that \c fish does not
support the use of environment variables as direct commands; \c eval can
be used to work around this.
\fish <pre>
set cmd ls set cmd ls
eval $cmd eval $cmd
\endfish </pre>

View File

@@ -1,15 +1,15 @@
\section exec exec - execute command in current process \section exec exec - execute command in current process
\subsection exec-synopsis Synopsis \subsection exec-synopsis Synopsis
\fish{synopsis} <tt>exec COMMAND [OPTIONS...]</tt>
exec COMMAND [OPTIONS...]
\endfish
\subsection exec-description Description \subsection exec-description Description
`exec` replaces the currently running shell with a new command. On successful completion, `exec` never returns. `exec` cannot be used inside a pipeline. \c exec replaces the currently running shell with a new command.
On successful completion, \c exec never returns. \c exec cannot be used
inside a pipeline.
\subsection exec-example Example \subsection exec-example Example
`exec emacs` starts up the emacs text editor, and exits `fish`. When emacs exits, the session will terminate. <tt>exec emacs</tt> starts up the emacs text editor, and exits \c fish.
When emacs exits, the session will terminate.

View File

@@ -1,12 +1,14 @@
\section exit exit - exit the shell \section exit exit - exit the shell
\subsection exit-synopsis Synopsis \subsection exit-synopsis Synopsis
\fish{synopsis} <tt>exit [STATUS]</tt>
exit [STATUS]
\endfish
\subsection exit-description Description \subsection exit-description Description
`exit` causes fish to exit. If `STATUS` is supplied, it will be converted to an integer and used as the exit code. Otherwise, the exit code will be that of the last command executed. \c exit causes fish to exit. If <tt>STATUS</tt> is
supplied, it will be converted to an integer and used as the exit
code. Otherwise, the exit code will be that of the last command executed.
If exit is called while sourcing a file (using the <a href="#source">source</a> builtin) the rest of the file will be skipped, but the shell itself will not exit. If exit is called while sourcing a file (using the <a
href="#source">.</a> builtin) the rest of the file will be skipped,
but the shell itself will not exit.

View File

@@ -1,10 +0,0 @@
\section false false - return an unsuccessful result
\subsection false-synopsis Synopsis
\fish{synopsis}
false
\endfish
\subsection false-description Description
`false` sets the exit status to 1.

View File

@@ -1,21 +1,5 @@
/** /** \page faq Frequently asked questions
\page faq Frequently asked questions
\htmlonly[block]
<div class="fish_left_bar">
<div class="logo"></div>
<div class="menu faq_menu">
\endhtmlonly
- <a href='#faq-envvar'>How do I set or clear an environment variable?</a>
- <a href='#faq-login-cmd'>How do I run a command every login? What's fish's equivalent to `.bashrc`?</a>
- <a href='#faq-prompt'>How do I set my prompt?</a>
- <a href='#faq-cmd-history'>How do I run a command from history?</a>
- <a href='#faq-subcommand'>How do I run a subcommand? The backtick doesn't work!</a>
- <a href='#faq-exit-status'>How do I get the exit status of a command?</a>
- <a href='#faq-single-env'>How do I set an environment variable for just one command?</a>
- <a href='#faq-customize-colors'>How do I customize my syntax highlighting colors?</a>
- <a href='#faq-update-manpage-completions'>How do I update man page completions?</a>
- <a href='#faq-cwd-symlink'>Why does cd, pwd and other fish commands always resolve symlinked directories to their canonical path?</a> - <a href='#faq-cwd-symlink'>Why does cd, pwd and other fish commands always resolve symlinked directories to their canonical path?</a>
- <a href='#faq-cd-implicit'>I accidentally entered a directory path and fish changed directory. What happened?</a> - <a href='#faq-cd-implicit'>I accidentally entered a directory path and fish changed directory. What happened?</a>
- <a href='#faq-open'>The open command doesn't work.</a> - <a href='#faq-open'>The open command doesn't work.</a>
@@ -25,203 +9,157 @@
- <a href='#faq-history'>Why doesn't history substitution ("!$" etc.) work?</a> - <a href='#faq-history'>Why doesn't history substitution ("!$" etc.) work?</a>
- <a href='#faq-uninstalling'>How do I uninstall fish?</a> - <a href='#faq-uninstalling'>How do I uninstall fish?</a>
\htmlonly[block]
</div>
</div>
<div class="faq fish_right_bar">
<h1 class="interior_title">Frequently Asked Questions</h1>
\endhtmlonly
\section faq-envvar How do I set or clear an environment variable?
Use the <a href="commands.html#set">`set`</a> command:
\fish{cli-dark}
set -x key value
set -e key
\endfish
\section faq-login-cmd How do I run a command every login? What's fish's equivalent to .bashrc?
Edit the file `~/.config/fish/config.fish`, creating it if it does not exist (Note the leading period).
<hr> <hr>
\section faq-prompt How do I set my prompt?
The prompt is the output of the `fish_prompt` function. Put it in `~/.config/fish/functions/fish_prompt.fish`. For example, a simple prompt is:
\fish{cli-dark}
function fish_prompt
set_color $fish_color_cwd
echo -n (prompt_pwd)
set_color normal
echo -n ' > '
end
\endfish
You can also use the Web configuration tool, <a href="commands.html#fish_config">`fish_config`</a>, to preview and choose from a gallery of sample prompts.
\section faq-cmd-history How do I run a command from history?
Type some part of the command, and then hit the @cursor_key{&uarr;,up} or @cursor_key{&darr;,down} arrow keys to navigate through history matches.
<hr>
\section faq-subcommand How do I run a subcommand? The backtick doesn't work!
`fish` uses parentheses for subcommands. For example:
\fish{cli-dark}
for i in (ls)
echo $i
end
\endfish
\section faq-exit-status How do I get the exit status of a command?
Use the `$status` variable. This replaces the `$?` variable used in some other shells.
<hr>
\section faq-single-env How do I set an environment variable for just one command?
<i>`SOME_VAR=1 command` produces an error: `Unknown command "SOME_VAR=1"`.</i>
Use the `env` command.
`env SOME_VAR=1 command`
You can also declare a local variable in a block:
\fish{cli-dark}
begin
set -lx SOME_VAR 1
command
end
\endfish
\section faq-customize-colors How do I customize my syntax highlighting colors?
Use the web configuration tool, <a href="commands.html#fish_config">`fish_config`</a>, or alter the <a href="index.html#variables-color">`fish_color` family of environment variables</a>.
<hr>
\section faq-update-manpage-completions How do I update man page completions?
Use the <a href="commands.html#fish_update_completions">`fish_update_completions`</a> command.
<hr>
\section faq-cwd-symlink Why does cd, $PWD and and various fish commands always resolve symlinked directories to their canonical path? \section faq-cwd-symlink Why does cd, $PWD and and various fish commands always resolve symlinked directories to their canonical path?
<i>For example if `~/images` is a symlink to `~/Documents/Images`, if I write '`cd images`', my prompt will say `~/Documents/Images`, not `~/images`.</i> <i>
For example if ~/images is a symlink to ~/Documents/Images, if I write
'cd images', my prompt will say ~/D/Images, not ~/images.
</i>
Because it is impossible to consistently keep symlinked directories unresolved. It is indeed possible to do this partially, and many other shells do so. But it was felt there are enough serious corner cases that this is a bad idea. Most such issues have to do with how '..' is handled, and are variations of the following example: Because it is impossible to consistently keep symlinked directories
unresolved. It is indeed possible to do this partially, and many other
shells do so. But it was felt there are enough serious corner cases
that this is a bad idea. Most such issues have to do with how '..' is
handled, and are varitations of the following example:
Writing `cd images; ls ..` given the above directory structure would list the contents of `~/Documents`, not of `~`, even though using `cd ..` changes the current directory to `~`, and the prompt, the `pwd` builtin and many other directory information sources suggest that the current directory is `~/images` and its parent is `~`. This issue is not possible to fix without either making every single command into a builtin, breaking Unix semantics or implementing kludges in every single command. This issue can also be seen when doing IO redirection. Writing <code>cd images; ls ..</code> given the above directory
structure would list the contents of ~/Documents, not of ~, even
though using <code>cd ..</code> changes the current directory to ~,
and the prompt, the pwd builtin and many other directory information
sources suggest that the current directory is ~/images and its
parent is ~. This issue is not possible to fix without either making
every single command into a builtin, breaking Unix semantics or
implementing kludges in every single command.
Another related issue is that many programs that operate on recursive directory trees, like the find command, silently ignore symlinked directories. For example, ```find $PWD -name '*.txt'``` silently fails in shells that don't resolve symlinked paths. This issue can also be seen when doing IO redirection.
Another related issue is that many programs that operate on recursive
directory trees, like the find command, silently ignore symlinked
directories. For example, <code>find $PWD -name '*.txt'</code>
silently fails in shells that don't resolve symlinked paths.
<hr> <hr>
\section faq-cd-implicit I accidentally entered a directory path and fish changed directory. What happened? \section faq-cd-implicit I accidentally entered a directory path and fish changed directory. What happened?
If fish is unable to locate a command with a given name, and it starts with '`.`', '`/`' or '`~`', fish will test if a directory of that name exists. If it does, it is implicitly assumed that you want to change working directory. For example, the fastest way to switch to your home directory is to simply press `~` and enter. If fish is unable to locate a command with a given name, and it starts with '.', '/' or '~', fish will
test if a directory of that name exists. If it does, it is implicitly
assumed that you want to change working directory. For example, the
fastest way to switch to your home directory is to simply press
<code>~</code> and enter.
<hr> <hr>
\section faq-open The open command doesn't work. \section faq-open The open command doesn't work.
The `open` command uses the MIME type database and the `.desktop` files used by Gnome and KDE to identify filetypes and default actions. If at least one of these environments is installed, but the open command is not working, this probably means that the relevant files are installed in a non-standard location. Consider <a href="index.html#more-help">asking for more help</a>. The \c open command uses the MIME type database and the <code>.desktop</code> files
used by Gnome and KDE to identify filetypes and default actions. If
at least one of these environments is installed, but the open command is
not working, this probably means that the relevant files are installed
in a non-standard location. Consider <a href="index.html#more-help">asking for
more help</a>.
<hr> <hr>
\section faq-default How do I make fish my default shell? \section faq-default How do I make fish my default shell?
If you installed fish manually (e.g. by compiling it, not by using a package manager), you first need to add fish to the list of shells by executing the following command (assuming you installed fish in /usr/local): If you installed fish manually (e.g. by compiling it, not by using a
package manager), you first need to add fish to the list of shells by
executing the following command (assuming you installed fish in
/usr/local) as root:
\fish{cli-dark}
echo /usr/local/bin/fish | sudo tee -a /etc/shells
\endfish
If you installed a prepackaged version of fish, the package manager should have already done this for you. <code>echo /usr/local/bin/fish >>/etc/shells</code>
If you installed a prepackaged version of fish, the package manager
should have already done this for you.
In order to change your default shell, type: In order to change your default shell, type:
\fish{cli-dark} <code>chsh -s /usr/local/bin/fish</code>
chsh -s /usr/local/bin/fish
\endfish
You may need to adjust the above path to e.g. `/usr/bin/fish`. Use the command `which fish` if you are unsure of where fish is installed. You may need to adjust the above path to e.g. \c /usr/bin/fish. Use the command <code>which fish</code> if you are unsure of where fish is installed.
Unfortunately, there is no way to make the changes take effect at once. You will need to log out and back in again. Unfortunately, there is no way to make the changes take effect at once.
You will need to log out and back in again.
<hr> <hr>
\section faq-titlebar I'm seeing weird output before each prompt when using screen. What's wrong? \section faq-titlebar I'm seeing weird output before each prompt when using screen. What's wrong?
Quick answer: Quick answer:
Run the following command in fish: Run the following command in fish:
\fish{cli-dark} <pre>
function fish_title; end; funcsave fish_title echo 'function fish_title;end' &gt; ~/.config/fish/config.fish
\endfish </pre>
Problem solved! Problem solved!
The long answer: The long answer:
Fish is trying to set the titlebar message of your terminal. While screen itself supports this feature, your terminal does not. Unfortunately, when the underlying terminal doesn't support setting the titlebar, screen simply passes through the escape codes and text to the underlying terminal instead of ignoring them. It is impossible to detect and resolve this problem from inside fish since fish has no way of knowing what the underlying terminal type is. For now, the only way to fix this is to unset the titlebar message, as suggested above. Fish is trying to set the titlebar message of your terminal. While
screen itself supports this feature, your terminal does
not. Unfortunately, when the underlying terminal doesn't support
setting the titlebar, screen simply passes through the escape codes
and text to the underlying terminal instead of ignoring them. It is
impossible detect and resolve this problem from inside fish since fish
has no way of knowing what the underlying terminal type is. For now,
the only way to fix this is to unset the titlebar message, as
suggested above.
Note that fish has a default titlebar message, which will be used if the fish_title function is undefined. So simply unsetting the fish_title function will not work. Note that fish has a default titlebar message, which will be used if
the fish_title function is undefined. So simply unsetting the
fish_title function will not work.
<hr> <hr>
\section faq-greeting How do I change the greeting message? \section faq-greeting How do I change the greeting message?
Change the value of the variable `fish_greeting` or create a `fish_greeting` function. For example, to remove the greeting use: Change the value of the variable fish_greeting. For example, to remove
the greeting use:
\fish{cli-dark} <pre>
set fish_greeting set fish_greeting
\endfish </pre>
<hr>
\section faq-history Why doesn't history substitution ("!$" etc.) work? \section faq-history Why doesn't history substitution ("!$" etc.) work?
Because history substitution is an awkward interface that was invented before interactive line editing was even possible. Fish drops it in favor of perfecting the interactive history recall interface. Switching requires a small change of habits: if you want to modify an old line/word, first recall it, then edit. E.g. don't type "sudo !!" - first press Up, then Home, then type "sudo ". Because history substitution is an awkward interface that was invented before
interactive line editing was even possible. Fish drops it in favor of
perfecting the interactive history recall interface. Switching requires a
small change of habits: if you want to modify an old line/word, first recall
it, then edit. E.g. don't type "sudo !!" - first press Up, then Home, then
type "sudo ".
Fish history recall is very simple yet effective: Fish history recall is very simple yet effective:
- As in any modern shell, the Up arrow, @cursor_key{&uarr;,Up} recalls whole lines, starting from the last line executed. A single press replaces "!!", later presses replace "!-3" and the like. - As in any modern shell, the Up arrow recalls whole lines, starting from the last line executed. A single press replaces "!!", later presses replace "!-3" and the like.
- If the line you want is far back in the history, type any part of the line and then press Up one or more times. This will constrain the recall to lines that include this text, and you will get to the line you want much faster. This replaces "!vi", "!?bar.c" and the like.
- If the line you want is far back in the history, type any part of the line and then press Up one or more times. This will constrain the recall to lines that include this text, and you will get to the line you want much faster. This replaces "!vi", "!?bar.c" and the like. - Alt+Up recalls individual arguments, starting from the last argument in the last line executed. A single press replaces "!$", later presses replace "!!:4" and the like.
- If the argument you want is far back in history (e.g. 2 lines back - that's a lot of words!), type any part of it and then press Alt+Up. This will show only arguments containing that part and you will get what you want much faster. Try it out, this is very convenient!
- @key{Alt,&uarr;,Up} recalls individual arguments, starting from the last argument in the last line executed. A single press replaces "!$", later presses replace "!!:4" and the like. - If you want to reuse several arguments from the same line ("!!:3*" and the like), consider recalling the whole line and removing what you don't need (Alt+D and Alt+Backspace are your friends).
- If the argument you want is far back in history (e.g. 2 lines back - that's a lot of words!), type any part of it and then press @key{Alt,&uarr;,Up}. This will show only arguments containing that part and you will get what you want much faster. Try it out, this is very convenient!
- If you want to reuse several arguments from the same line ("!!:3*" and the like), consider recalling the whole line and removing what you don't need (@key{Alt,D} and @key{Alt,Backspace} are your friends).
See <a href='index.html#editor'>documentation</a> for more details about line editing in fish. See <a href='index.html#editor'>documentation</a> for more details about line editing in fish.
<hr> <hr>
\section faq-uninstalling Uninstalling fish \section faq-uninstalling Uninstalling fish
Should you wish to uninstall fish, first ensure fish is not set as your shell. Run `chsh -s /bin/bash` if you are not sure. Should you wish to uninstall fish, first ensure fish is not set as your shell. Run <code>chsh -s /bin/bash</code> if you are not sure.
Next, do the following (assuming fish was installed to /usr/local): Next, do the following (assuming fish was installed to /usr/local):
\fish{cli-dark} <pre>
rm -Rf /usr/local/etc/fish /usr/local/share/fish ~/.config/fish rm -Rf /usr/local/etc/fish /usr/local/share/fish ~/.config/fish
rm /usr/local/share/man/man1/fish*.1 rm /usr/local/share/man/man1/fish*.1
cd /usr/local/bin cd /usr/local/bin
rm -f fish fish_indent rm -f fish mimedb fish_pager fishd fish_indent
\endfish </pre>
<hr>
\section faq-reserved-chars Unicode private-use characters reserved by fish
Fish reserves the <a href="http://www.unicode.org/faq/private_use.html">Unicode private-use character range</a> from U+F600 thru U+F73F for internal use. Any attempt to feed characters in that range to fish will result in them being replaced by the Unicode "replacement character" U+FFFD. This includes both interactive input as well as any file read by fish (but not programs run by fish).
\htmlonly[block]
</div>
\endhtmlonly
*/ */

View File

@@ -1,17 +1,14 @@
\section fg fg - bring job to foreground \section fg fg - bring job to foreground
\subsection fg-synopsis Synopsis \subsection fg-synopsis Synopsis
\fish{synopsis} <tt>fg [PID]</tt>
fg [PID]
\endfish
\subsection fg-description Description \subsection fg-description Description
\c fg brings the specified <a href="index.html#syntax-job-control">job</a> to the foreground, resuming it if it is stopped. While a foreground job is
`fg` brings the specified <a href="index.html#syntax-job-control">job</a> to the foreground, resuming it if it is stopped. While a foreground job is executed, fish is suspended. If no job is specified, the last job to be used is put in the foreground. If PID is specified, the job with the specified group ID is put in the foreground. executed, fish is suspended. If no job is specified, the last job to be used is put in the foreground. If PID is specified, the job with the specified group ID is put in the foreground.
The PID of the desired process is usually found by using <a href="index.html#expand-process">process expansion</a>. The PID of the desired process is usually found by using <a href="index.html#expand-process">process expansion</a>.
\subsection fg-example Example \subsection fg-example Example
`fg %1` will put the job with job ID 1 in the foreground. <tt>fg \%1</tt> will put the job with job ID 1 in the foreground.

View File

@@ -1,28 +1,25 @@
\section fish fish - the friendly interactive shell \section fish fish - the friendly interactive shell
\subsection fish-synopsis Synopsis \subsection fish-synopsis Synopsis
\fish{synopsis} fish [-h] [-v] [-c command] [FILE [ARGUMENTS...]]
fish [OPTIONS] [-c command] [FILE [ARGUMENTS...]]
\endfish
\subsection fish-description Description \subsection fish-description Description
`fish` is a command-line shell written mainly with interactive use in mind. The full manual is available <a href='index.html'>in HTML</a> by using the <a href='#help'>help</a> command from inside fish. \c fish is a command-line shell written mainly with interactive use in mind. The
full manual is available <a href='index.html'>in HTML</a> by using the
<a href='#help'>help</a> command from inside fish.
The following options are available: The following options are available:
- `-c` or `--command=COMMANDS` evaluate the specified commands instead of reading from the commandline - <code>-c</code> or <code>--command=COMMANDS</code> evaluate the specified commands instead of reading from the commandline
- <code>-d</code> or <code>--debug-level=DEBUG_LEVEL</code> specify the verbosity level of fish. A higher number means higher verbosity. The default level is 1.
- <code>-h</code> or <code>--help</code> display help and exit
- <code>-i</code> or <code>--interactive</code> specify that fish is to run in interactive mode
- <code>-l</code> or <code>--login</code> specify that fish is to run as a login shell
- <code>-n</code> or <code>--no-execute</code> do not execute any commands, only perform syntax checking
- <code>-p</code> or <code>--profile=PROFILE_FILE</code> when fish exits, output timing information on all executed commands to the specified file
- <code>-v</code> or <code>--version</code> display version and exit
- `-d` or `--debug-level=DEBUG_LEVEL` specify the verbosity level of fish. A higher number means higher verbosity. The default level is 1. The fish exit status is generally the exit status of the last
foreground command. If fish is exiting because of a parse error, the
- `-i` or `--interactive` specify that fish is to run in interactive mode exit status is 127.
- `-l` or `--login` specify that fish is to run as a login shell
- `-n` or `--no-execute` do not execute any commands, only perform syntax checking
- `-p` or `--profile=PROFILE_FILE` when fish exits, output timing information on all executed commands to the specified file
- `-v` or `--version` display version and exit
The fish exit status is generally the exit status of the last foreground command. If fish is exiting because of a parse error, the exit status is 127.

View File

@@ -2,17 +2,21 @@
\subsection fish_config-description Description \subsection fish_config-description Description
`fish_config` starts the web-based configuration interface. \c fish_config starts the web-based configuration interface.
The web interface allows you to view your functions, variables and history, and to make changes to your prompt and color configuration. The web interface allows you to view your functions, variables and history, and
to make changes to your prompt and color configuration.
`fish_config` starts a local web server and then opens a web browser window; when you have finished, close the browser window and then press the Enter key to terminate the configuration session. \c fish_config starts a local web server and then opens a web browser window; when
you have finished, close the browser window and then press the Enter key to
terminate the configuration session.
`fish_config` optionally accepts name of the initial configuration tab. For e.g. `fish_config history` will start configuration interface with history tab. There are no parameters for <code>fish_config</code>.
If the `BROWSER` environment variable is set, it will be used as the name of the web browser to open instead of the system default.
If the \c BROWSER environment variable is set, it will be used as the name
of the web browser to open instead of the system default.
\subsection fish_config-example Example \subsection fish_config-example Example
`fish_config` opens a new web browser window and allows you to configure certain fish settings. \c fish_config opens a new web browser window and allows you to configure certain
fish settings.

View File

@@ -1,22 +1,17 @@
\section fish_indent fish_indent - indenter and prettifier \section fish_indent fish_indent - indenter and prettifier
\subsection fish_indent-synopsis Synopsis \subsection fish_indent-synopsis Synopsis
\fish{synopsis} <tt>fish_indent [options]</tt>
fish_indent [OPTIONS]
\endfish
\subsection fish_indent-description Description \subsection fish_indent-description Description
`fish_indent` is used to indent a piece of fish code. `fish_indent` reads commands from standard input and outputs them to standard output. \c fish_indent is used to indent a piece of fish
code. \c fish_indent reads commands from standard input and outputs
them to standard output.
The following options are available: The following options are available:
- `-d` or `--dump` dumps information about the parsed fish commands to stderr - <tt>-h</tt> or <tt>--help</tt> displays this help message and then exits
- <tt>-i</tt> or <tt>--no-indent</tt> do not indent commands
- <tt>-v</tt> or <tt>--version</tt> displays the current fish version and then exits
- `-i` or `--no-indent` do not indent commands; only reformat to one job per line
- `-v` or `--version` displays the current fish version and then exits
- `--ansi` colorizes the output using ANSI escape sequences, appropriate for the current $TERM, using the colors defined in the environment (such as `$fish_color_command`).
- `--html` outputs HTML, which supports syntax highlighting if the appropriate CSS is defined. The CSS class names are the same as the variable names, such as `fish_color_command`

7
doc_src/fish_pager.txt Normal file
View File

@@ -0,0 +1,7 @@
\section fish_pager fish_pager - internal command used by fish
\subsection fish_pager-description Description
\c fish_pager is used internally by fish. It should not be used by other
commands, as its interface is liable to change in the future.

View File

@@ -1,29 +1,28 @@
\section fish_prompt fish_prompt - define the appearance of the command line prompt \section fish_prompt fish_prompt - define the appearance of the command line prompt
\subsection fish_prompt-synopsis Synopsis \subsection fish_prompt-synopsis Synopsis
\fish{synopsis} <pre>function fish_prompt
function fish_prompt
... ...
end end</pre>
\endfish
\subsection fish_prompt-description Description \subsection fish_prompt-description Description
By defining the `fish_prompt` function, the user can choose a custom prompt. The `fish_prompt` function is executed when the prompt is to be shown, and the output is used as a prompt. By defining the \c fish_prompt function, the user can choose a custom
prompt. The \c fish_prompt function is executed when the prompt is to
be shown, and the output is used as a prompt.
The exit status of commands within `fish_prompt` will not modify the value of <a href="index.html#variables-status">$status</a> outside of the `fish_prompt` function. The exit status of commands within \c fish_prompt will not modify the value of <a href="index.html#variables-status">$status</a> outside of the \c fish_prompt function.
`fish` ships with a number of example prompts that can be chosen with the `fish_config` command.
\c fish ships with a number of example prompts that can be chosen with the
\c fish_config command.
\subsection fish_prompt-example Example \subsection fish_prompt-example Example
A simple prompt: A simple prompt:
\fish <pre>
function fish_prompt -d "Write out the prompt" function fish_prompt -d "Write out the prompt"
printf '%s@%s%s%s%s> ' (whoami) (hostname | cut -d . -f 1) \ printf '\%s\@\%s\%s\%s\%s> ' (whoami) (hostname|cut -d . -f 1) (set_color \$fish_color_cwd) (prompt_pwd) (set_color normal)
(set_color $fish_color_cwd) (prompt_pwd) (set_color normal)
end end
\endfish </pre>

Some files were not shown because too many files have changed in this diff Show More