Mostrando entradas con la etiqueta terminal. Mostrar todas las entradas
arch and manjaro temp size
create this script and run:
source: https://gist.github.com/ertseyhan/618ab7998bdb66fd6c58
create this script and run:
Terminal:
#!/bin/bash
sudo mount -o remount,size=40G,noatime /tmp
echo "Done. Please use 'df -h' to make sure folder size is increased."
source: https://gist.github.com/ertseyhan/618ab7998bdb66fd6c58
how to connect your home server to a domain with cloudflare
this tutorial is very extend for has various points:
well cloudflare is a server dns that allows you to manage our dns for free for the domains we use and create sub-domains, although it has more cloudflare tools, we will use some of them
after you register:
1. Add the site
select plan to use:
when you finalize the purchase for 0$ you can see that:
press to button continue
now you must change dns nameserver in your domain
for example in my domain https://my.freenom.com/
change to Name-servers
to
check the name-servers is working
2. Auto update your dynamic ip
if you have a dynamic ip, you need send the new ip to cloudflare for this use a small script bash for run with crontab in Gnu/Linux the best system :)
well for this we looking 3 elements
a) api key
b) id zone dns (for domain)
c) id domain in zone dns
now we use curl and api for get the id domain
https://api.cloudflare.com/
list dns records
https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records
get the attribute id and use after dns_record at url
you remember get the id of your domain example ramdontest.ml, the others are sub-domain and we interest update only the domain because the sub-domain has the same ip, because use dns type CNAME
update the ip
script bash
3. Add sub-domains to domain
Add the sub-domain
this is very important, change the domain to dns only, this is you can connect for ssh with domain or you can a sub-domain change to dns only and connect to ssh
Example:
4. Select to type of encryption
These options are listed from least (Off) to most secure (Full SSL (Strict)). All options are available in all customer plans.
Off: No secure connection between your visitor and Cloudflare, and no secure connection between Cloudflare and your web server either. This means that visitors can only view your website over HTTP, and any visitor attempting to connect via HTTPS will receive a HTTP 301 Redirect to the plain HTTP version of your website.
Flexible SSL: A Secure connection between your visitor and Cloudflare, but no secure connection between Cloudflare and your web server. You don't need to have an SSL certificate on your web server, but your visitors still see the site as being HTTPS enabled. This option is not recommended if you have any sensitive information on your website. This setting will only work for port 443->80, not for the other ports we support like 2053. It should only be used as a last resort if you are not able to setup SSL on your own web server. Be aware it can cause issues when you decide to switch away from it: How do I fix the infinite redirect loop...
Full SSL: A secure connection between your visitor and Cloudflare, plus a secure connection (but not authenticated) between Cloudflare and your web server. You will need to have your server configured to answer HTTPS connections, with at least a self-signed certificate. The authenticity of the certificate is not verified: from Cloudflare’s point of view (when we connect to your origin web server), it’s the equivalent of bypassing this error message. But as long as the address of your origin web server is correct in your DNS settings, you know that we’re connecting to your web server, and not someone else’s.
Full SSL (Strict): A secure connection between your visitor and Cloudflare, plus a secure and authenticated connection between Cloudflare and your web server. You will need to have your server configured to answer HTTPS connections, with a valid SSL certificate. This certificate must be signed by a certificate authority that is trusted by Cloudflare, have an expiration date in the future, and respond for the request domain name (hostname). If you've added a CNAME record for the hostname on Cloudflare, the certificate's Common Name or SAN may also match the CNAME target.
Strict (SSL-Only Origin Pull): Enterprise only This mode has the same certificate requirements as Full (Strict) and will also upgrade all connections between Cloudflare and the origin from HTTP to HTTPS, even if the original content requested is over HTTP.
Origin CA certificates, generated by Cloudflare, can be used with either the Full or Full(strict) options as they are trusted by Cloudflare. You can find more information about Origin CA certificates below:
if you want use Flexible SSL dont need config more, whole is ready.
now configuration with full mode
select to full mode
create certificate
copy the code pem and code key and paste in your server
you should have this
5. Configuration encryption pem and key with nginx
links: https://support.cloudflare.com/hc/en-us/articles/200170416-What-do-the-SSL-options-mean-
this tutorial is very extend for has various points:
- Add site
- Auto update your dynamic ip
- Add sub-domains to domain
- Select to type of encryption
- Configuration encryption pem and key with nginx
well cloudflare is a server dns that allows you to manage our dns for free for the domains we use and create sub-domains, although it has more cloudflare tools, we will use some of them
after you register:
1. Add the site
select plan to use:
when you finalize the purchase for 0$ you can see that:
press to button continue
now you must change dns nameserver in your domain
for example in my domain https://my.freenom.com/
change to Name-servers
to
check the name-servers is working
2. Auto update your dynamic ip
if you have a dynamic ip, you need send the new ip to cloudflare for this use a small script bash for run with crontab in Gnu/Linux the best system :)
well for this we looking 3 elements
a) api key
b) id zone dns (for domain)
c) id domain in zone dns
now we use curl and api for get the id domain
https://api.cloudflare.com/
list dns records
https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records
get the attribute id and use after dns_record at url
Terminal:
curl -X GET "https://api.cloudflare.com/client/v4/zones/YOUR_ZONE_ID/dns_records?type=A&name=YOUR_DOMAIN" -H "X-Auth-Email: YOUR_EMAIL" -H "X-Auth-Key: YOUR_API_KEY" -H "Content-Type: application/json"
you remember get the id of your domain example ramdontest.ml, the others are sub-domain and we interest update only the domain because the sub-domain has the same ip, because use dns type CNAME
update the ip
Terminal:
curl -X PUT "https://api.cloudflare.com/client/v4/zones/YOUR_ZONE_ID/dns_records/YOUR_ID_DOMAIN" \ -H "X-Auth-Email: user@example.com" \ -H "X-Auth-Key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data '{"type":"A","name":"example.com","content":"127.0.0.1","ttl":1,"proxied":false}'the word or number with red is because you change 1 to 120 or true - false, for balance with cloudflare or without balance
script bash
Terminal:
#!/bin/sh ipNow=$(/sbin/ifconfig enp2s0 | grep -i 'Direc. inet' | cut -d ":" -f 2 | cut -d " " -f 1) ipOld="" UBICATION_LOGS="/opt/logs/" ejecutarCodigo() { { echo "From: Server Update IP <server@YOUR-DOMAIN.COM>" echo "Sender: YOUR-MAIL@GMAIL.COM" echo "To: YOUR-MAIL@GMAIL.COM" echo "Subject: The server change ip" echo echo "The server change ip "$ipOld" to "$ipNow } | /usr/sbin/ssmtp YOUR-MAIL@gmail.com #enviar email } while read line; do ipOld=$line done <$UBICATION_LOGS"ipOld.js" echo $ipOld" - "$ipNow if [ $ipOld != $ipNow ]; then #loadwebs.tk curl -X PUT "https://api.cloudflare.com/client/v4/zones/YOUR_ID_ZONE/dns_records/YOUR_ID_DOMAIN" \ -H "X-Auth-Email: YOUR-MAIL@gmail.com" \ -H "X-Auth-Key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ --data '{"type":"A","name":"YOUR_DOMAIN","content":'\"$ipNow\"',"ttl":1,"proxied":false}' ejecutarCodigo else echo "NO" fi
3. Add sub-domains to domain
this is very important, change the domain to dns only, this is you can connect for ssh with domain or you can a sub-domain change to dns only and connect to ssh
Example:
4. Select to type of encryption
These options are listed from least (Off) to most secure (Full SSL (Strict)). All options are available in all customer plans.
Off: No secure connection between your visitor and Cloudflare, and no secure connection between Cloudflare and your web server either. This means that visitors can only view your website over HTTP, and any visitor attempting to connect via HTTPS will receive a HTTP 301 Redirect to the plain HTTP version of your website.
Flexible SSL: A Secure connection between your visitor and Cloudflare, but no secure connection between Cloudflare and your web server. You don't need to have an SSL certificate on your web server, but your visitors still see the site as being HTTPS enabled. This option is not recommended if you have any sensitive information on your website. This setting will only work for port 443->80, not for the other ports we support like 2053. It should only be used as a last resort if you are not able to setup SSL on your own web server. Be aware it can cause issues when you decide to switch away from it: How do I fix the infinite redirect loop...
Full SSL: A secure connection between your visitor and Cloudflare, plus a secure connection (but not authenticated) between Cloudflare and your web server. You will need to have your server configured to answer HTTPS connections, with at least a self-signed certificate. The authenticity of the certificate is not verified: from Cloudflare’s point of view (when we connect to your origin web server), it’s the equivalent of bypassing this error message. But as long as the address of your origin web server is correct in your DNS settings, you know that we’re connecting to your web server, and not someone else’s.
Full SSL (Strict): A secure connection between your visitor and Cloudflare, plus a secure and authenticated connection between Cloudflare and your web server. You will need to have your server configured to answer HTTPS connections, with a valid SSL certificate. This certificate must be signed by a certificate authority that is trusted by Cloudflare, have an expiration date in the future, and respond for the request domain name (hostname). If you've added a CNAME record for the hostname on Cloudflare, the certificate's Common Name or SAN may also match the CNAME target.
Strict (SSL-Only Origin Pull): Enterprise only This mode has the same certificate requirements as Full (Strict) and will also upgrade all connections between Cloudflare and the origin from HTTP to HTTPS, even if the original content requested is over HTTP.
Origin CA certificates, generated by Cloudflare, can be used with either the Full or Full(strict) options as they are trusted by Cloudflare. You can find more information about Origin CA certificates below:
if you want use Flexible SSL dont need config more, whole is ready.
now configuration with full mode
select to full mode
create certificate
copy the code pem and code key and paste in your server
you should have this
5. Configuration encryption pem and key with nginx
Terminal:
server { listen 443 ssl; server_name first.ramdontest.ml; root /var/www; index index.php index.html index.htm index.nginx-debian.html; ssl_certificate /opt/ssl/ramdontest.pem; ssl_certificate_key /opt/ssl/ramdontest.key; access_log /opt/logs/ramdontest.ml.access_log.js; error_log /opt/logs/ramdontest.ml.error_log.js; rewrite_log on; location / { proxy_pass http://localhost:3202; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; } }
links: https://support.cloudflare.com/hc/en-us/articles/200170416-What-do-the-SSL-options-mean-
virtualbox manjaro error /sbin/vboxconfig solved kernel 4.14
first check to version kernel
my kernel is 4.14.* for this, i install
now activate modprobe
first check to version kernel
Terminal:
uname -a
my kernel is 4.14.* for this, i install
Terminal:
sudo pacman -S linux414-virtualbox-host-modules
now activate modprobe
Terminal:
sudo modprobe vboxdrv
Terminal:
sudo adduser your_home_user vboxusers
Terminal:
sudo usermod -aG vboxusers your_home_user
that's all |
ssh crear jaula para usuario sftp y ftp en ubuntu
primero configuramos ssh
https://cirelramos.blogspot.com/2015/09/instalacion-open-ssh-ubuntu-server.html
Instalamos vsftpd
Agregamos al archivo
Lo siguiente:
ClientAliveInterval 20
ClientAliveCountMax 5
UsePAM yes
Match Group jail
ForceCommand internal-sftp
ChrootDirectory /home/%u
X11Forwarding no
AllowTcpForwarding no
El contenido anterior especifica que todos los usuarios que pertenezcan al grupo de usuario jail solo pueden conectarse por sftp en su directorio home
Creamos el grupo de usuario jail
configuramos ftp para que tambien solo quede en el home del usuario para eso editamos el archivo
Borramos su contenido y agregamos las siguientes lineas:
#listen_port=2121 #puedes cambiar el puerto de conexion si es necesario
listen=NO
listen_ipv6=YES
anonymous_enable=NO
local_enable=YES
write_enable=YES
dirmessage_enable=YES
use_localtime=YES
xferlog_enable=YES
connect_from_port_20=YES
secure_chroot_dir=/var/run/vsftpd/empty
pam_service_name=ftpd
allow_writeable_chroot=YES
chroot_local_user=YES
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
ssl_enable=NO
Reiniciamos los servicios
Creamos el usuario
Asignamos una contraseña
Opcional:
Creamos una carpeta en bird
realizamos un enlace de /home/bird/html a /var/www/bird esto se realiza para poder tener como un "acceso directo desde el apache o nginx a nuestro directorio html en el home del usuario
Creamos el enlace simbolico
con eso ya tenemos un usuario encapsulado para editar solo sus archivos
Conectarnos por sftp
si queremos eliminar el usuario
primero configuramos ssh
https://cirelramos.blogspot.com/2015/09/instalacion-open-ssh-ubuntu-server.html
Instalamos vsftpd
Terminal:
sudo apt-get install vsftpd openssh-server
Agregamos al archivo
Terminal:
sudo nano /etc/ssh/sshd_config
Lo siguiente:
ClientAliveInterval 20
ClientAliveCountMax 5
UsePAM yes
Match Group jail
ForceCommand internal-sftp
ChrootDirectory /home/%u
X11Forwarding no
AllowTcpForwarding no
El contenido anterior especifica que todos los usuarios que pertenezcan al grupo de usuario jail solo pueden conectarse por sftp en su directorio home
Creamos el grupo de usuario jail
Terminal:
sudo groupadd jail
configuramos ftp para que tambien solo quede en el home del usuario para eso editamos el archivo
Terminal:
sudo nano /etc/vsftpd.conf
Borramos su contenido y agregamos las siguientes lineas:
#listen_port=2121 #puedes cambiar el puerto de conexion si es necesario
listen=NO
listen_ipv6=YES
anonymous_enable=NO
local_enable=YES
write_enable=YES
dirmessage_enable=YES
use_localtime=YES
xferlog_enable=YES
connect_from_port_20=YES
secure_chroot_dir=/var/run/vsftpd/empty
pam_service_name=ftpd
allow_writeable_chroot=YES
chroot_local_user=YES
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
ssl_enable=NO
Reiniciamos los servicios
Terminal:
sudo /etc/init.d/ssh restart
Terminal:
sudo systemctl restart vsftpd
Creamos el usuario
Terminal:
useradd -s /bin/rbash -d /home/bird/ birdCreamos el home del usuario
Terminal:
sudo mkdir -p /home/bird/Realizamos el cambio de propietarios
Terminal:
sudo chown bird:www-data /home/bird/cambiamos los permisos
Terminal:
sudo chmod 770 /home/bird/
Asignamos una contraseña
Terminal:
sudo passwd birdAgregamos al usuario bird el grupo jail
Terminal:
sudo adduser bird jail
Opcional:
Creamos una carpeta en bird
Terminal:
sudo mkdir -p /home/bird/html/
realizamos un enlace de /home/bird/html a /var/www/bird esto se realiza para poder tener como un "acceso directo desde el apache o nginx a nuestro directorio html en el home del usuario
Creamos el enlace simbolico
Terminal:
sudo ln -s /home/bird/html /var/www/birdRealizamos el cambio de propietarios de nuevo
Terminal:
sudo chown bird:www-data -R /home/bird/cambiamos los permisos de nuevo
Terminal:
sudo chmod 770 -R /home/bird/
con eso ya tenemos un usuario encapsulado para editar solo sus archivos
Conectarnos por sftp
Terminal:
sftp -oPort=22 bird@midominio.com
si queremos eliminar el usuario
Terminal:
sudo userdel -r bird
Vim
Instalamos los Plugins
chequeamos si python esta activo con
si no tienes activo el python y te encuentras en debia o alguna de sus derivadas puedes solucionarlo con
ahora instalamos el gestor de plugins para vim
para instalar los plugins declarados en la configuracion ejecutamos
luego dentro de vim presionamos los dos puntos -> :
nos deberia quedar asi
https://vimawesome.com/
yo he realizado una configuracion personal y se instala de una manera muy facil, corriendo alguno de los siguientes scripts
entrar en vim y ejecutar
:PlugInstall
:PlugInstall
asi instalamos todos los Plugins que se encuentran en la configuración
instalamos los paquetes npm necesarios para el eslint
Comandos comunes
new ruta-del-archivo para dividir la pantalla horizontalmente
vnew ruta-del-archivo para dividir la pantalla verticalmente
:shell regresar a la terminal
tabn, para irnos a la siguiente pestaña.
tabp, para irnos a la pestaña previa.
tabfirst, para irnos a la primera pestaña.
tablast, para irnos a la última pestaña.
:tabnew Crea una nueva pestaña vacía.
:tabedit fichero Abre el fichero especificado en una nueva pestaña.
:tabclose Cerrar la pestaña actual (también con :q!).
:tabnext [n] Saltar a la siguiente pestaña (o a la enesima siguiente).
:tabprev [n] Saltar a la anterior pestaña (o a la enesima anterior).
:e Crea un nuevo buffer.
:bclose Cerrar el buffer actual.
:bnext [n] Saltar a el siguiente buffer .
:bprev [n] Saltar a el anterior buffer .
Atajos mas comunes
Switch pestaña
gt (En modo comando) Saltar a la siguiente pestaña. En gvim también sirve Ctrl+AvPag.
gT (En modo comando) Saltar a la anterior pestaña. En gvim también sirve Ctrl+RePag.
Ngt (En modo comando) Saltar a la pestaña número N.
:tabs Mostrar una lista de pestañas abiertas.
:tabdo comando Ejecuta el comando en todas las pestañas abiertas, abortando en caso de error.
%= formatear todo el codigo
4= formatear 4 lineas de codigo
V (select rows) = formatear las lineas seleccionadas
"qp -> imprimir el macro realizado
Fuzzy FinderCtrlp
if you want use in bash or zsh type
vim ** and press
tab
NerdTree
F5
para ver las opciones del menu
m
Comandos Emmet
Ctrlz,
za
abrir un fold completo
zR
cerrar un fold completo
zC
para colocar todo el documento con fold
ggvGzC
para hacer unfold a todo el documento
ggvGzR
http://vim.wikia.com/wiki/Search_patterns
http://vim.wikia.com/wiki/Delete_all_lines_containing_a_pattern
cortar y pegar
presionas V para entrar el en el modo VISUAL luego para seleccionar
en linea: CTRL+V
en bloques CTRL+Q
para cortar dd
para cortar dentro de comillas di"
para copiar yy
para pegar p
Comentar Lineas
# Nos situamos al principio de la primera línea que queremos comentar.
# Activamos el modo "VISUAL BLOCK".
Ctrl + V
# Con la flecha del teclado vamos bajando hasta la última línea a comentar.
# Entramos en modo "INSERT".
Shift + I
# Introducimos el símbolo de comentario, según el tipo de código, por ejemplo -> # (en bash)
# Veremos que solo se añade el carácter a la primera línea, tranquilos.
# Salimos del modo "INSERT".
Esc
# Automáticamente se añadirá el símbolo # a todas las líneas seleccionadas con "VISUAL BLOCK"
Descomentar Lineas
# Nos situamos al principio de la primera línea que queremos descomentar.
# Activamos el modo "VISUAL BLOCK".
Ctrl + V
# Con la flecha del teclado vamos bajando hasta la última línea a descomentar.
# Directamente borramos el símbolo que comenta el código en bash.
Supr
# Automáticamente se borrará el símbolo # a todas las líneas seleccionadas con "VISUAL BLOCK"
https://www.youtube.com/watch?v=5r6yzFEXajQ
https://drive.google.com/file/d/1eYBTBTOedXVNqxXlfhZCjfngtypQPFxB/view?usp=sharing
https://blogs.technet.microsoft.com/jessicadeen/linux/macos-ohmyzsh-tmux-vim-iterm2-powerlevel9k-badass-terminal/
http://vim.wikia.com/wiki/Copy,_cut_and_paste
https://www.marblestation.com/?p=910
http://www.sromero.org/wiki/linux/aplicaciones/manual_vim
Instalamos los Plugins
Terminal:
sudo apt-get install vim
chequeamos si python esta activo con
Terminal:
vim --version
si no tienes activo el python y te encuentras en debia o alguna de sus derivadas puedes solucionarlo con
Terminal:
sudo apt-get remove vim
Terminal:
sudo apt-get install vim-nox
ahora instalamos el gestor de plugins para vim
Terminal:
git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
luego agregamos las siguientes lineas al archivo de configuracion
Terminal:
nano ~/.vimrc
Texto a copiar:
set nocompatible " be iMproved, required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')
" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'
" The following are examples of different formats supported.
" Keep Plugin commands between vundle#begin/end.
" plugin on GitHub repo
Plugin 'tpope/vim-fugitive'
" plugin from http://vim-scripts.org/vim/scripts.html
" Plugin 'L9'
" Git plugin not hosted on GitHub
Plugin 'git://git.wincent.com/command-t.git'
" git repos on your local machine (i.e. when working on your own plugin)
Plugin 'file:///home/gmarik/path/to/plugin'
" The sparkup vim script is in a subdirectory of this repo called vim.
" Pass the path to set the runtimepath properly.
Plugin 'rstacruz/sparkup', {'rtp': 'vim/'}
" Install L9 and avoid a Naming conflict if you've already installed a
" different version somewhere else.
" Plugin 'ascenator/L9', {'name': 'newL9'}
" All of your Plugins must be added before the following line
call vundle#end() " required
filetype plugin indent on " required
" To ignore plugin indent changes, instead use:
"filetype plugin on
"
" Brief help
" :PluginList - lists configured plugins
" :PluginInstall - installs plugins; append `!` to update or just :PluginUpdate
" :PluginSearch foo - searches for foo; append `!` to refresh local cache
" :PluginClean - confirms removal of unused plugins; append `!` to auto-approve removal
"
" see :h vundle for more details or wiki for FAQ
" Put your non-Plugin stuff after this line
para instalar los plugins declarados en la configuracion ejecutamos
Terminal:
vim
luego dentro de vim presionamos los dos puntos -> :
nos deberia quedar asi
Terminal:
:PluginInstallpresionamos enter y esperamos que instale los plugins, para encontrar mas plugins puedes visitar la siguiente pagina web
https://vimawesome.com/
yo he realizado una configuracion personal y se instala de una manera muy facil, corriendo alguno de los siguientes scripts
Terminal:
sudo wget https://gitlab.com/cirelramos/oh-my-vim/raw/master/quick-install.sh -O - | sudo bash
entrar en vim y ejecutar
Terminal:
sudo apt-get install build-essential cmake python-dev python3-dev
Terminal:
vim
:PlugInstall
:PlugInstall
asi instalamos todos los Plugins que se encuentran en la configuración
instalamos los paquetes npm necesarios para el eslint
Terminal:
npm install -g babel-eslint esformatter-quotes eslint-plugin-babel eslint-plugin-jsx-a11y node-gyp webpack csslint eslint eslint-plugin-import eslint-plugin-react npm-check-updates esformatter eslint-config-airbnb eslint-plugin-jest jshint js-beautify update -f
Terminal:
ln -s /usr/local/bin/eslint /usr/bin/eslint
Comandos comunes
new ruta-del-archivo para dividir la pantalla horizontalmente
vnew ruta-del-archivo para dividir la pantalla verticalmente
:shell regresar a la terminal
tabn, para irnos a la siguiente pestaña.
tabp, para irnos a la pestaña previa.
tabfirst, para irnos a la primera pestaña.
tablast, para irnos a la última pestaña.
:tabnew Crea una nueva pestaña vacía.
:tabedit fichero Abre el fichero especificado en una nueva pestaña.
:tabclose Cerrar la pestaña actual (también con :q!).
:tabnext [n] Saltar a la siguiente pestaña (o a la enesima siguiente).
:tabprev [n] Saltar a la anterior pestaña (o a la enesima anterior).
:e Crea un nuevo buffer.
:bclose Cerrar el buffer actual.
:bnext [n] Saltar a el siguiente buffer .
:bprev [n] Saltar a el anterior buffer .
Atajos mas comunes
Switch pestaña
gt (En modo comando) Saltar a la siguiente pestaña. En gvim también sirve Ctrl+AvPag.
gT (En modo comando) Saltar a la anterior pestaña. En gvim también sirve Ctrl+RePag.
Ngt (En modo comando) Saltar a la pestaña número N.
:tabs Mostrar una lista de pestañas abiertas.
:tabdo comando Ejecuta el comando en todas las pestañas abiertas, abortando en caso de error.
%= formatear todo el codigo
4= formatear 4 lineas de codigo
V (select rows) = formatear las lineas seleccionadas
"qp -> imprimir el macro realizado
Fuzzy FinderCtrlp
if you want use in bash or zsh type
vim ** and press
tab
NerdTree
F5
para ver las opciones del menu
m
Comandos Emmet
Ctrlz,
fold o pestañas en el codigo
para cerrar o abrir un foldza
abrir un fold completo
zR
cerrar un fold completo
zC
para colocar todo el documento con fold
ggvGzC
para hacer unfold a todo el documento
ggvGzR
- zo opens a fold at the cursor.
- zShift+o opens all folds at the cursor.
- zc closes a fold at the cursor.
- zm increases the
foldlevel
by one. - zShift+m closes all open folds.
- zr decreases the
foldlevel
by one. - zShift+r decreases the
foldlevel
to zero -- all folds will be open.
ver todos los map
:verbose map <key>
Buscar una palabra en especifico
:/\<me\>en ese caso seria la palabra "me" para conocer mas pattern
http://vim.wikia.com/wiki/Search_patterns
Eliminar la linea completa que contenga la busqueda "profile"
g/profile/d
http://vim.wikia.com/wiki/Delete_all_lines_containing_a_patterncortar y pegar
presionas V para entrar el en el modo VISUAL luego para seleccionar
en linea: CTRL+V
en bloques CTRL+Q
para cortar dd
para cortar dentro de comillas di"
para copiar yy
para pegar p
Una vez tenemos abierto vim y estamos editando un archivo debemos conocer diversos comandos para poder utilizar el entorno. El editor se puede encontrar en 3 modos diferentes:
- Modo normal (Normal mode): Se pueden utilizar ciertas combinaciones de teclas para realizar ciertas acciones. Para acceder a este modo presionar escape.
- Modo inserción (Insertion mode): Se puede insertar (insert) o sobreescribir el texto (append). Para acceder a este modo presionar ‘i’, ‘a’ o la tecla ‘insert’ (1 vez = insert, 2 veces = append).
- Modo comando (Command mode): Se puede utilizar cualquier comando SED además de funciones propias de Vim. Para acceder a este modo se debe estar en modo normal y pulsar ‘:’, a continuación se escribirá nuestra petición.
- Modo visual (visual mode): Se puede selecionar texto para tratarlo en conjunto. Para acceder a este modo se debe estar en modo normal y pulsar ‘v’.
Modo Normal
- Desplazamiento con los cursores del teclado o con h (izquierda), j (arriba), k (abajo) y l (derecha)
- Última línea
- Primera línea
- Deshacer
- Rehacer
- Buscar un texto
- Buscar el texto donde se encuentra el cursor
- Buscar el texto donde se encuentra el cursor en sentido inverso
- Repetir última búsqueda
- Repetir última búsqueda en sentido contrario
- Dividir la pantalla horizontalmente en 2:
- Dividir la pantalla verticalmente en 2:
- Crear un nuevo archivo en una pantalla dividida horizontalmente:
- Cerrar la división actual
- Moverse a la ventana de arriba (j), abajo (k), izquierda (h) o derecha (l):
- Hacer todas las ventanas del mismo tamaño
- Incrementar/Decrementar la altura de la ventana actual
- Nueva pestaña
- Siguiente o anterior pestaña
- Cerrar pestaña
- Seleccionar todo el texto
- Establecer una marca con el nombre ‘a’
- Ir a la marca ‘a’
- Ir a la última línea modificada
G
gg
u
CTRL+r
/texto[ENTER]
%
#
n
N
CTRL+ws
CTRL+wv
CTRL+wn
CTRL+wq
CTRL+w{j,k,h,l} ó CTRL+w{cursores del teclado}
CTRL+w=
CTRL+{+,-}
CTRL+t
CTRL+n
CTRL+p
CTRL+p
CTRL+c
ggVG
ó
vggG
ó
vggG
ma
‘a
‘.
Modo Inserción
- Autocompletar palabra en base al texto ya existente
- Indentar
- Desindentar
CTRL+N y CTRL+P (p.ej. “hola hCTRL+N” resultado “hola hola”)
CTRL+t
CTRL+d
Modo Comando
Pulsar [ENTER] después de cada comando
- Ir a la linea 25
- Salir
- Salir cerrando todos los ficheros abiertos
- Guardar
- Salir guardando
- Salir sin guardar
- Guardar en fichero de solo lectura (sólo root)
- Guardar con otro nombre
- Editar archivo
- Cerrar archivo
- Navegar a partir de un directorio
- :/palabraAbuscar
- :/palabraAbuscar\c ignorando minusculas y mayusculas
- Substituir una cadena de texto A por B (si alguna de estas cadenas contiene caracteres que tengan algun significado especial como por ejemplo ‘/’ se debe anular antes la funcionalidad de este con \, por ejemplo, substituir los ‘/’ por ‘.’ seria :s/\//./)
- mix order list values
%!shuf - Substituir una cadena de texto A por B en todo el texto
- Substituir una cadena de texto A por B en todo el texto aceptando confirmacion
:25
:q
:qa
:w
:wq
:q!
:w!
:w archivo
:e archivo
:bdelete
:e directorio
:Explore
:Explore
:%s/A/B/ (p.ej. :s/hola/adios)
:%s/A/B/g
:%s/A/B/gc
- Eliminar linea por busqueda
g/profile/d
- Substituir una cadena de texto A por B entre la linea 2 y 10
- Activar la inserción en “modo paste”, esto permite pegar cosas al documento (usando el ratón) de forma que no tabule lo que pegamos, ya que si ese texto ya esta tabulado lo único que hace es pegar desordenando el texto.
- Desactivar la inserción en “modo paste”
- Cortar las líneas que no caben en pantalla.
- No cortar las líneas que no caben en pantalla
- Dividir pantalla horizontalmente
- Dividir pantalla verticalmente
<c-w>w
moverse por los paneles. Pulsaremos de forma conjunta la tecla control yw
, soltaremos las teclas y pulsaremosw
de nuevo.<c-w>h
ir al panel de la izquierda.<c-w>j
ir al panel de abajo.<c-w>k
ir al panel de arriba.<c-w>l
ir al panel de la derecha.<c-w>c
cerrar panel. También hace lo mismo:cl[ose]
.<c-w>o
mantener el panel activo, cerrando los demás. También nos sirve:on[ly]
.<c-w>=
iguala la altura y anchura de los paneles.<c-w>_
maximiza la altura del panel activo.<c-w>|
maximiza el alncho del panel activo.[N]<c-w>_
la alturá será de[N]
filas.[N]<c-w>|
la anchura será de[N]
columnas.- Crear nueva pantalla dividida
- Quedarse solo con la ventana actual y ocultar el resto
- Listar todos los ficheros abiertos (buffers)
- Ir al buffer X (los numeros aparecen al hacer un :files o :buffers *en plural*)
- Ir al buffer X (pulsar tabulador para autocompletar)
- Ayuda
:2,10s/A/B/g
:set paste
:set nopaste
:set wrap
:set nowrap
:split
:vsplit
:new
:only
:files ó :buffers
:file X ó :buffer X
:b X
:help ó :help termino
Modo Visual
Como ya hemos comentado, para acceder a este modo se debe estar en modo normal y pulsar ‘v’. No obstante, si en lugar de ‘v’ pulsamos ‘Ctrl+v’ pasaremos al modo visual en bloque (permite seleccionar un bloque de texto por columnas en lugar de por filas). Y si pulsamos ‘gv’ se repetirá la última selección.
- Seleccionar texto utilizando h(izquierda), j (arriba), k (abajo) y l (derecha) o con los cursores del teclado.
- Es posible aplicar las mismas instrucciones vista en el modo comando y modo normal, pero esto solo se realizará sobre el texto seleccionado.
- Si seleccionamos texto y pasamos a modo comando pulsando ‘:’ se nos mostrar una linea como esta “:’ <,’>”, no debemos borrar estos símbolos ya que es la forma de reconocer vim que estamos aplicando el comando al texto seleccionado.
- Copiar el texto selecionado
- Copiar el texto selecionado en el portapapeles del sistema (teclear el + también)
- Cortar el texto seleccionado
- Pegar el texto copiado o cortado. Debemos estar en modo normal, se pasará automáticamente a ese modo despues de copiar o cortar con ‘y’ o ‘d’.
- Pegar el texto desde el portapapeles del sistema (teclear el + también)
- Indentar
- Indentar
- Modo visual seleccionando columnas en lugar de lineas
- Insertar texto delante de la columna
y
“+y
d
p
“+p
>>
<<
CTRL+v
CTRL+v SHIFT+i ‘texto’ ESC
Corrector ortográfico
Por defecto, vim dispone de corrector para Inglés pero si activamos otros idiomas, el editor nos pregunará si deseamos descargar los correspondientes diccionarios automáticamente.
- Activar corrector
- Desactivar corrector
- Seleccionamos idioma
:set spell
:set nospell
:set spelllang=es
:set spelllang=ca
:set spelllang=en
:set spelllang=fr
:set spelllang=ca
:set spelllang=en
:set spelllang=fr
Las palabras incorrectas se marcaran en color rojo y podremos interaccionar en modo normal:
- Siguiente palabra incorrecta
- Previa palabra incorrecta
- Sugerencias de corrección para una palabra
- Añadir una palabra al diccionario
- Borrar una palabra del diccionario
]s
[s
z=
zg
zw
Comentar Lineas
# Activamos el modo "VISUAL BLOCK".
Ctrl + V
# Con la flecha del teclado vamos bajando hasta la última línea a comentar.
# Entramos en modo "INSERT".
Shift + I
# Introducimos el símbolo de comentario, según el tipo de código, por ejemplo -> # (en bash)
# Veremos que solo se añade el carácter a la primera línea, tranquilos.
# Salimos del modo "INSERT".
Esc
# Automáticamente se añadirá el símbolo # a todas las líneas seleccionadas con "VISUAL BLOCK"
Descomentar Lineas
# Nos situamos al principio de la primera línea que queremos descomentar.
# Activamos el modo "VISUAL BLOCK".
Ctrl + V
# Con la flecha del teclado vamos bajando hasta la última línea a descomentar.
# Directamente borramos el símbolo que comenta el código en bash.
Supr
# Automáticamente se borrará el símbolo # a todas las líneas seleccionadas con "VISUAL BLOCK"
En la página de Vim se puede encontrar más información, incluso scripts que añaden funcionalidades interesantes. Recomendables:
- MiniBuffExplorer: Añade una barra con el listado de ficheros (buffers) abiertos (F2 para visualizarlo, CTRL+n y CTRL+p para el siguiente/anterior segun establecido en el archivo de configuración de este artículo).
- TagList: Acceso a funciones/métodos para diversos lenguajes de programación mediante :Tlist (Requiere apt-get install exuberant-ctags) o F4 (segun la configuración indicada en este artículo)
- NERD Comment: Comentar lineas o bloques de código utilizando ,cc / ,cu / ,c[espacio]
- NERD Tree: Alternativa al navegador de ficheros :Explore visualizable mediante :NERDTreeToggle o F3/shift-F3
- PowerLine: Línea de estado con colores e indicaciones configurables.
- VCScommand: Comandos para controlar el repositorio de control de versiones (Subversion, Git…) desde vim.
https://www.youtube.com/watch?v=5r6yzFEXajQ
https://drive.google.com/file/d/1eYBTBTOedXVNqxXlfhZCjfngtypQPFxB/view?usp=sharing
https://blogs.technet.microsoft.com/jessicadeen/linux/macos-ohmyzsh-tmux-vim-iterm2-powerlevel9k-badass-terminal/
http://vim.wikia.com/wiki/Copy,_cut_and_paste
https://www.marblestation.com/?p=910
http://www.sromero.org/wiki/linux/aplicaciones/manual_vim
Suscribirse a:
Entradas
(
Atom
)